Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values from nested dictionaries in python

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()]
like image 947
f_ficarola Avatar asked Jun 01 '14 15:06

f_ficarola


People also ask

How would you access and store all of the keys in this dictionary at once?

The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Parameters: There are no parameters. Returns: A view object is returned that displays all the keys.

How do you make a nested dictionary dynamically in Python?

Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.


2 Answers

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.

like image 161
Richard Avatar answered Sep 21 '22 15:09

Richard


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']]
like image 43
Ankur Ankan Avatar answered Sep 22 '22 15:09

Ankur Ankan