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

旧城冷巷雨未停 提交于 2020-01-03 17:19:09

问题


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.


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/17585898/python-list-of-dictionaries-how-to-get-values-of-a-specific-key-for-multiple-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!