python – Accessing value inside nested dictionaries
python – Accessing value inside nested dictionaries
As always in python, there are of course several ways to do it, but there is one obvious way to do it.
tmpdict[ONE][TWO][THREE]
is the obvious way to do it.
When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.
If you just want to just save you repetative typing, you can of course alias a subset of the dict:
>>> two_dict = tmpdict[ONE][TWO] # now you can just write two_dict for tmpdict[ONE][TWO]
>>> two_dict[spam] = 23
>>> tmpdict
{ONE: {TWO: {THREE: 10, spam: 23}}}
You can use the get() on each dict. Make sure that you have added the None check for each access.
python – Accessing value inside nested dictionaries
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={foo:{bar:{one:1, two:2}, misc:[1,2,3]}, foo2:123}
>>> get_nested(dct, foo, bar, one)
1
>>> get_nested(dct, foo, bar, two)
2
>>> get_nested(dct, foo, misc)
[1, 2, 3]
>>> get_nested(dct, foo, missing)
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.