Last active
March 4, 2019 09:29
-
-
Save MMohan1/0cf0036d0b87abba8bd7a2dabbff7bb5 to your computer and use it in GitHub Desktop.
Python update and get data from nested dict
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
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