Adham
Adham

Reputation: 342

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.

Upvotes: 4

Views: 10852

Answers (3)

Atul Arvind
Atul Arvind

Reputation: 16733

>>> [x.get('key3') for x in dict_list[1:3]]
['dict2_value3', 'dict3_value3']

Upvotes: 7

inspectorG4dget
inspectorG4dget

Reputation: 113905

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

Upvotes: 3

zhangyangyu
zhangyangyu

Reputation: 8610

[x['key3'] for x in dict_list[1:3]]

Upvotes: 2

Related Questions