Reputation: 54848
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. (Every dictionary has a key).
How can I do this?
Edit : There is a sample (JSON representation) of the input
[
[
{
"lat": 45.1845931,
"lgt": 5.7316984,
"name": "Chavant",
"sens": "",
"line" : [],
"stationID" : ""
},
{
"lat": 45.1845898,
"lgt": 5.731746,
"name": "Chavant",
"sens": "",
"line" : [],
"stationID" : ""
}
],
[
{
"lat": 45.1868233,
"lgt": 5.7565727,
"name": "Neyrpic - Belledonne",
"sens": "",
"line" : [],
"stationID" : ""
},
{
"lat": 45.1867322,
"lgt": 5.7568569,
"name": "Neyrpic - Belledonne",
"sens": "",
"line" : [],
"stationID" : ""
}
]
]
As output I'd like to have a list of names.
PS: Data under ODBL.
Upvotes: 1
Views: 99
Reputation: 22561
If you need all names in flat list:
response = # your big list
[d.get('name') for lst in response for d in lst]
if you want to get result with inner list:
[[d.get('name') for d in lst] for lst in response]
Upvotes: 2
Reputation: 22882
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).
Upvotes: 1