skip to Main Content

I’m trying to remove the keys from a mongoengine Document in python:

document.update(unset__name=True)
document.update(unset__surname=True)
document.update(unset__dob=True)
...

but instead of the above I would like to loop through them and use a variable, something like:

document.update(unset__<key>=True)

Is this possible?

2

Answers


  1. with a map ? you can build it and put as function kwargs

    unset_map = {
        "unset_key": True
    }
    document.update(**unset_map)
    
    Login or Signup to reply.
  2. yes, this is feasible by destructuring a dictionary.
    For example, like in there:

    d = { "p1": 11, "p2": 12}
    def f(p1,p2):
        print(f"p1={p1}, p2={p2}")
    
    f(p2=100,p1=10)
    f(**d)
    

    In your case, you will simply have to build a dictionnary with all the keys you want to destroy, by building the correct string:

    def delete_key(key_name: str):
        d = { f"unset__{key_name}": True }
        document.update(**d)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search