I am trying to retrieve a single level from a nested dictionary. So for instance, given the dictionary below, I would expect to see the following results for the first and second level.
nested_dict = {
'foo':'bar',
'baz':{
'foo':'baz'
}}
# level 0
{'foo':'bar'}
# level 1
{'foo':'baz'}
I can retrieve the first level using a dict comprehension:
{k:v for (k,v) in nested_dict.items() if type(v) is not dict}
>>> {'foo':'bar'}
Or retrieve a specified level using a recursion:
def get_level(nested_dict, level):
if level == 0:
return {k:v for (k,v) in nested_dict.items() if type(v) is not dict}
else:
this_level = {}
for (k,v) in nested_dict.items():
if type(v) is dict:
this_level.update(v)
return get_level(this_level, level - 1)
get_level(nested_dict, 1)
>>> {'foo':'baz'}
I am now wondering if there is a more Pythonic/clean/out of the box way to retrieve the levels of nested dictionaries (as I already did above), if necessary with help of a package.