简体   繁体   中英

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

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 ]

I think you need a ternary expression here;

[dic['a'] if 'a' in dic else 'No Data' for dic in alist]

or use dict.get :

[dic.get('a','No Data') for dic in alist]

Here is a way without a list comprehension for the functional programming fans

>>> alist=[{'a':'1a', 'b':'1b'},{'a':'2a','b':'2b'}, {'a':'3a','b':'3b'}]
>>> from operator import itemgetter
>>> list(map(itemgetter('a'), alist))
['1a', '2a', '3a']

To get the "No Data", it's much easier to use the list comprehension

>>> [item.get('a', 'No Data') for item in alist]
['1a', '2a', '3a']

This works because dict.get lets you specify a default argument in case the key is not found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM