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

python

Solution

[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.

Problem

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'`

Original source