简体   繁体   中英

How to do this list/dict comprehension in python

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

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.

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