简体   繁体   中英

How to create a list of a given key from dictionary

I want to create a list that holds all dictionary values mapped to a given key. I only know how to extract values from topmost key, like so:

>>> dict1 = {"key1": 1, "key2":2, "key3": 3}
>>> list1 = dict1.values()
>>> print(list1)
dict_values([1, 2, 3])
>>> 
>>> 
>>> dict2 = {"key1": {"id": 1, "val": 100}, "key2": {"id": 2, "val": 200}}
>>> list2 = dict2.values()
>>> print(list2)
dict_values([{'id': 1, 'val': 100}, {'id': 2, 'val': 200}])

I want to be able to extract all values from dict2 that are mapped to key = "id". in this case:

[1, 2]

How can this be achieved?

You can loop over the values and for each one, lookup based on the 'id' key

>>> [d['id'] for d in  dict2.values()]
[1, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM