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.
>>> [x.get('key3') for x in dict_list[1:3]]
['dict2_value3', 'dict3_value3']
[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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With