Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list from a list of dictionaries using comprehension for specific key value

Tags:

python

How can I write a comprehension to extract all values of key='a'?

alist=[{'a':'1a', 'b':'1b'},{'a':'2a','b':'2b'}, {'a':'3a','b':'3b'}]

The following works but I just hacked until I got what I want. Not a good way to learn.

[alist['a'] for alist in alist if 'a' in alist]

in the comprehension I have been trying to use if key='a' in alist else 'No data'

like image 383
Mahendra Gunawardena Avatar asked Dec 06 '22 06:12

Mahendra Gunawardena


2 Answers

[elem['a'] for elem in alist if 'a' in elem]

might be a clearer way of phrasing what you have above.

The "for elem in alist" part will iterate over alist, allowing this to look through each dictionary in alist.

Then, the "if 'a' in elem" will ensure that the key 'a' is in the dictionary before the lookup occurs, so that you don't get a KeyError from trying to look up an element that doesn't exist in the dictionary.

Finally, taking elem['a'] gives you the value in each dictionary with key 'a'. This whole statement will then give the list of values in each of the dictionaries with key 'a'.

Hope this makes it a bit clearer.

like image 83
qaphla Avatar answered Jan 13 '23 11:01

qaphla


You can do:

alist=[{'a':'1a', 'b':'1b'},{'a':'2a','b':'2b'}, {'a':'3a','b':'3b'}]
new_list = [a.get('a') for a in alist]

If you want to restrict it only to dictionary with a key a,

new_list = [a.get('a') for a in alist if a.get('a')]

Based on gnibbler's suggestion:

new_list = [a.get('a') for a in alist if 'a' in a ]
like image 37
karthikr Avatar answered Jan 13 '23 13:01

karthikr