Get all values from nested dictionaries in python

折月煮酒 提交于 2019-12-05 02:29:52
Richard

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}}}
list(NestedDictValues(a))

The output is:

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

which is all of the values.

You could use a simple list comprehension:

[a['b']['c'][key]['answer'] for key in a['b']['c'].keys()]
Out[11]: ['answer1', 'answer2', 'answer3']

If you want to get all the answers and conf etc. You could do:

[[a['b']['c'][key][type] for key in a['b']['c'].keys()] for type in a['b']['c']['d'].keys()]
Out[15]: [['conf1', 'conf2', 'conf3'], ['answer1', 'answer2', 'answer3']]

I would do that using recursive generator function:

def d_values(d, depth):
    if depth == 1:
        for i in d.values():
            yield i
    else:
        for v in d.values():
            if isinstance(v, dict):
                for i in d_values(v, depth-1):
                    yield i

Example:

>>> list(d_values({1: {2: 3, 4: 5}}, 2))
[3, 5]

In your case, this would give a dictionary like {'answer': answer1, 'conf': conf1} as each item, so you can use:

list(d['answer'] for d in d_values(a, 3))

Just to give an answer to this topic, copying my solution from the "updating status" of my question:

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

Hope this can help.

list(map(lambda key:  a['b']['c'][key],  a['b']['c'].keys()))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!