2

I'm curious if there is a way to recursively explore nested dictionaries in python. By this I mean, say we have an example such as the below:

d = {'a':{'b':{'c':[1,2,3]}}}

What code would be necessary to get the contents of the innermost dictionary {'c':[1,2,3]}, traversing through a and b? In this case, it's not too much effort to write d['a']['b']['c'] but what if there was an arbitrarily large number of nested dictionaries, such that this was impossible/overly cumbersome.

My gut instinct is that I would need to create a general tree class with key and payload attributes, parsing the dictionary and storing it in my object, which I could design to be parsed using DFS, BFS, etc.

j9000
  • 386
  • 1
  • 3
  • 14

1 Answers1

2

Here's a recursive approach. The idea is to check if the current's dictionary value is an instance of a dict, if it is call the same function with the values as input, otherwise return the dictionary:

def get_inner_dict(d):
    for _, v in d.items():
        if isinstance(v, dict):
            return get_inner_dict(v) 
        else:
            return d

get_inner_dict(d)
# {'c': [1, 2, 3]}
yatu
  • 86,083
  • 12
  • 84
  • 139