Last active
August 29, 2015 14:11
-
-
Save Visgean/e536e466207bf439983a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 protected]'} | |
>>> convert_dict_to_update(data) | |
{'set__email': '[email protected]'} | |
: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