Skip to content

Instantly share code, notes, and snippets.

@geudrik
Created September 30, 2016 15:29
Show Gist options
  • Save geudrik/0b0a898371a2492fc0aa3187c27e3926 to your computer and use it in GitHub Desktop.
Save geudrik/0b0a898371a2492fc0aa3187c27e3926 to your computer and use it in GitHub Desktop.
Get value for a nested key, given a map list (list of keys to traverse)
# Taken from https://stackoverflow.com/questions/14692690/access-python-nested-dictionary-items-via-a-list-of-keys
# Reproduced for my own benefit later
data_dict = {
"a":{
"r": 1,
"s": 2,
"t": 3
},
"b":{
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
"w": 3
}
}
# Get a value from data_dict, given a list of keys to traverse
def get_from_dict(data_dict, map_list):
return reduce(lambda d, k: d[k], map_list, data_dict)
# Create a key and set a value, at any deapth
def setInDict(data_dict, map_list, value):
getFromDict(data_dict, map_list[:-1])[map_list[-1]] = value
>>> getFromDict(data_dict, ["a", "r"])
1
>>> getFromDict(data_dict, ["b", "v", "y"])
2
>>> setInDict(data_dict, ["b", "v", "w"], 4)
>>> import pprint
>>> pprint.pprint(data_dict)
{'a': {'r': 1, 's': 2, 't': 3},
'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment