Skip to content Skip to sidebar Skip to footer

List Of Values For A Key In List Of List Of Dictionaries?

Suppose I have a list of a list of dictionaries. I'm pretty sure Python has a nice and short way (without writing 2 for loops) to retrieve the value associated with the key. (Ever

Solution 1:

If you need all names in flat list:

response = # your big list
[d.get('name') forlstin response fordin lst]

if you want to get result with inner list:

[[d.get('name') fordin lst] forlstin response]

Solution 2:

Call your list of lists of dictionaries L. Then you can retrieve all names using a list comprehension by iterating through each sublist and then each dictionary.

Demo

>>> vals = [ d['name'] for sublist in L for d in sublist ]
>>> vals
[u'Chavant', u'Chavant', u'Neyrpic - Belledonne', u'Neyrpic - Belledonne']

Note that this returns a flattened list of all names (and that 'Chavant' appears twice, since it appears twice in your input).

Post a Comment for "List Of Values For A Key In List Of List Of Dictionaries?"