It seems more pythonic to use a for
loop.
See the quote from What’s New In Python 3.0.
Removed
reduce()
. Usefunctools.reduce()
if you really need it; however, 99 percent of the time an explicitfor
loop is more readable.
def nested_get(dic, keys):
for key in keys:
dic = dic[key]
return dic
Note that the accepted solution doesn't set non-existing nested keys (it raises KeyError
). Using the approach below will create non-existing nodes instead:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
The code works in both Python 2 and 3.