Skip to content

Instantly share code, notes, and snippets.

@MMohan1
Last active March 4, 2019 09:29
Show Gist options
  • Save MMohan1/0cf0036d0b87abba8bd7a2dabbff7bb5 to your computer and use it in GitHub Desktop.
Save MMohan1/0cf0036d0b87abba8bd7a2dabbff7bb5 to your computer and use it in GitHub Desktop.
Python update and get data from nested dict
from functools import reduce
def deep_get(dictionary, keys_list, default=None):
keys = ".".join(keys_list)
return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."),
dictionary)
def setInDict(dataDict, mapList, value):
if mapList[:-1]:
if deep_get(dataDict, mapList[:-1]):
deep_get(dataDict, mapList[:-1])[mapList[-1]] = value
else:
setInDict(dataDict, mapList[:-1], {mapList[-1]: value})
else:
dataDict[mapList[0]] = value
return dataDict
dict_name = {"name": {"fname": "sharma"}}
abc = setInDict(dict_name, ["name", "fname"], "manmohan")
print abc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment