Reputation: 12500
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
Upvotes: 2
Views: 6844
Reputation: 56855
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
Upvotes: 1
Reputation: 8813
List comprehensions are very powerful at this sort of list manipulation:
print([d[x] for x in l])
Upvotes: 1
Reputation: 44
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
Upvotes: 0