Python - create a list from a list of dictionaries using comprehension for a specific key value

Disclaimer: I'm new to python programming (only 2 days)

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

How can I write an understanding to extract all the key = 'a values ​​??

The following works, but I just hacked until I got what I want. Not the best way to learn.

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

in the understanding that I tried to use if key = 'a' in alist else 'No data'

Thanks for your help in advance.

+4
source share
4 answers
 [elem['a'] for elem in alist if 'a' in elem] 

may be a clearer way of articulating what you have above.

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

Then "if" a "in elem" will ensure that the key "a" is in the dictionary before starting the search, so that you will not get a KeyError from trying to find an item that does not work, t in the dictionary.

Finally, taking elem ['a'], you will get a value in each dictionary with the key "a". Then the whole operator will provide a list of values ​​in each of the dictionaries with the key "a".

Hope this improves a bit.

+8
source

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 limit it to just a dictionary with the a key,

 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 ] 
+3
source

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] 
+1
source

Here is a non-list method for 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 "No data", it’s much easier to use list comprehension.

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

This works because dict.get allows dict.get to specify a default argument if the key is not found.

+1
source

Source: https://habr.com/ru/post/1490615/


All Articles