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'
[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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With