Skip to content

Instantly share code, notes, and snippets.

@Visgean
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Visgean/e536e466207bf439983a to your computer and use it in GitHub Desktop.
Save Visgean/e536e466207bf439983a to your computer and use it in GitHub Desktop.
def convert_dict_to_update(dictionary, roots=None, return_dict=None):
"""
Returns a new dict that can be used in Document.update(**dict),
this is used for updating MongoEngine documents with dictionary
serialized from json.
>>> data = {'email' : 'email@example.com'}
>>> convert_dict_to_update(data)
{'set__email': 'email@example.com'}
:param dictionary: dictionary with update parameters
:param roots: roots of nested documents - used for recursion
:param return_dict: used for recursion
:return: new dict
"""
if return_dict is None:
return_dict = {}
if roots is None:
roots = []
for key, value in dictionary.iteritems():
if isinstance(value, dict):
roots.append(key)
convert_dict_to_update(value, roots=roots, return_dict=return_dict)
roots.remove(key) # go one level down in the recursion
else:
if roots:
set_key_name = 'set__{roots}__{key}'.format(
roots='__'.join(roots), key=key)
else:
set_key_name = 'set__{key}'.format(key=key)
return_dict[set_key_name] = value
return return_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment