Skip to content

Get all values from nested dictionaries in python

An answer to this question on Stack Overflow.

Question

I have some dictionaries of dictionaries, like this:

a['b']['c']['d']['answer'] = answer1
a['b']['c']['e']['answer'] = answer2
a['b']['c']['f']['answer'] = answer3
....
a['b']['c']['d']['conf'] = conf1
a['b']['c']['e']['conf'] = conf2
a['b']['c']['f']['conf'] = conf3

Is there a fast way to get a list of values of all answers for all elements at the third level (d,e,f)?

Specifically I'd like to know if there's any mechanism implementing a wildcard (e.g., a['b']['c']['*']['answer'].values()

update The fastest way I've found till now is:

[x['answer'] for x in a['b']['c'].values()]

Answer

In Python3 we can build a simple generator for this:

def NestedDictValues(d):
  for v in d.values():
    if isinstance(v, dict):
      yield from NestedDictValues(v)
    else:
      yield v
a={4:1,6:2,7:{8:3,9:4,5:{10:5},2:6,6:{2:7,1:8}}}
print(list(NestedDictValues(a)))

The output is:

[1, 2, 3, 4, 5, 6, 7, 8]

which is all of the values.