Linda
Linda

Reputation: 2405

Get value of dictionary in a list in a dictionary

I want to get a value to a known key in a Dictionary. Simple but this dictionary is in a list of dictionarys and the list is in a dictionary.

example:

{u 'd1': 1, 'd2':2 , 'd3': [{'e1':'muh','e2':'mia' ...},{'e1':'wuff', 'e2':'kickeriki'...},...]}

and i want to get all values of key 'e2' in 'd3'. Is there a super fast way?

EDIT*: thank you!

results:

Blender: 8.82148742676e-06
Oscar:   4.05311584473e-06

I will take list comp.

Upvotes: 2

Views: 191

Answers (2)

Veronica Cornejo
Veronica Cornejo

Reputation: 488

A short answer based in list comprehensions is:

[ d[k] for d in data['d3'] if k in d ]

Where data is the data structure in your example and k the key you are looking for.

This alternative does not assume k is present in all subordinate dictionaries.

Tested with

data= {'d1': 1, 'd2':2 , 'd3': [{},{'e1':'muh','e2':'mia'},{},{'e1':'wuff', 'e2':'kickeriki'},{}]}
k= 'e1'

Result

['muh', 'wuff']

If clause if k in d is eliminated, this results in an exception as d[k] is executed for a dictionary that does not contain k.

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

Try this, using list comprehensions:

d = { 'd1': 1,
      'd2': 2 ,
      'd3': [{'e1':'muh','e2':'mia'}, {'e1':'wuff', 'e2':'kickeriki'}]}

[inner['e2'] for inner in d['d3']]
=> ['mia', 'kickeriki']

Upvotes: 3

Related Questions