Reputation: 10996
I am creating a python dictionary as follows:
d= {i : chr(65+i) for i in range(4)}
Now output of d
is {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
I have an list of keys that I want to look up as follows:
l = [0, 1]
Now what I want to do is create another list which contains the values corresponding to these keys and I wanted to know if there was a pythonic way to do so using list or dict comprehensions.
I can do something as follows:
[x for x in d[0]]
However, I do not know how to iterate over the entries of my list in this setting. I tried:
[x for x in d[a] for a in l] # name 'a' not defined
[x for x in d[for a in l]] # invalid syntax
Upvotes: 0
Views: 87
Reputation: 1121386
You want to iterate over l
, so use for element in l
. Then look stuff up in your dictionary in the left-hand side, in the value-producing expression:
[d[element] for element in l]
Note that a dictionary mapping consecutive integers starting at 0 to letters isn't all that efficient; you may as well make it a list:
num_to_letter = [chr(65 + i) for i in range(4)]
This still maps 0
to 'A'
, 1
to 'B'
, etc, but without a hashing step.
Upvotes: 3