Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list of dictionaries, how to get values of a specific key for multiple items of the list?

I have a list of dictionaries like:

dict_list = [{'key1': 'dict1_value1', 'key2': 'dict1_value2', 'key3': 'dict1_value3'},
{'key1': 'dict2_value1', 'key2': 'dict2_value2', 'key3': 'dict2_value3'},
{'key1': 'dict3_value1', 'key2': 'dict3_value2', 'key3': 'dict3_value3'},
{'key1': 'dict4_value1', 'key2': 'dict4_value2', 'key3': 'dict4_value3'},
{'key1': 'dict5_value1', 'key2': 'dict5_value2', 'key3': 'dict5_value3'}]

getting the value for 'key3' for the second list item is like:

dict_list[1]['key3']
dict2_value3

and also the code below returns items 2:4 from the list:

dict_list[1:3]

What if I want to get values for 'key3' for multiple items from the list. like

dict_list[1:3]['key3']

something similar to what we do in MATLAB.

like image 297
Adham Avatar asked Dec 15 '22 08:12

Adham


2 Answers

>>> [x.get('key3') for x in dict_list[1:3]]
['dict2_value3', 'dict3_value3']
like image 175
Atul Arvind Avatar answered May 17 '23 09:05

Atul Arvind


[dict_list[i]['key3'] for i in xrange(1,3)]

OR

[operator.itemgetter('key3')(dict_list[i]) for i in range(1,3)]

OR

map(operator.itemgetter('key3'), itertools.islice(dict_list, 1,3))
like image 26
inspectorG4dget Avatar answered May 17 '23 07:05

inspectorG4dget