CHRD
CHRD

Reputation: 1957

Best way to get values from nested dictionary in python

Suppose I have a dict:

d = {'A': {'field': 1}, 'B': {'field': 2}}

How can I list the values of all field keys? Expected result:

[1, 2]

Upvotes: 1

Views: 212

Answers (4)

Sahith Kurapati
Sahith Kurapati

Reputation: 1715

You can do it in one line simply with list comprehension like so:

fields = [x["field"] for x in d.values() if 'field' in x.keys()]

Hope this helps :)

Upvotes: 3

Udaya Prakash
Udaya Prakash

Reputation: 541

If you want a clearer readable code than one-liners:

d = {'A': {'field': 1}, 'B': {'field': 2}}
fields = d.values()
result = []
for val in fields:
  result.append(val['field'])

print(result)

Repl link

Upvotes: 1

Jojin
Jojin

Reputation: 124

Use a list comprehension like this:

>>> d
{'A': {'field': 1}, 'B': {'field': 2}}
>>> [d[e]['field'] for e in d]
[1, 2]

Upvotes: 1

Alexander Lekontsev
Alexander Lekontsev

Reputation: 1012

[value['field'] for _, value in d.items() if 'field' in value]

Upvotes: 2

Related Questions