简体   繁体   中英

Select values from a dictionary using a list of keys

How can I get values from a dictionary using the keys that are in a list?

For example, given a dictionary:

d = {
  'a': 1,
  'b': 2,
  'c': 3
}

and a list:

l = ['a', 'c']

I would like output:

1
3

You can use a list comprehension to select the values per key that exist in the dictionary:

>>> d = {
...     'a': 1,
...     'b': 2,
...     'c': 3,
... }
>>> L = ['a', 'c']
>>> result = [d[x] for x in L if x in d]
>>> result
[1, 3]
>>> for val in result:
...     print(val)
...
1
3

Here's the answer in for loop:

for j in l:
 print(d[j])

列表推导式在这种列表操作中非常强大:

print([d[x] for x in l])

You can do something like this

print(d[l[0]])

or for more readability

idx = l[0]
print(d[idx])

You will need to loop every item to get all the values, and be sure the index exists.


If you want to check if a given key exists in the dictionary, you can do:

'a' in d

which will return True, or

'd' in d

will return False in your example. But either way, the value you are using will be coming from the indexed search in your list, or the variable you pass that value to.

idx in d

would return either False or True depending on the value stored in idx

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