dictionary - How to do this list/dict comprehension in python -


i creating python dictionary follows:

d= {i : chr(65+i) in range(4)} 

now output of d {0: 'a', 1: 'b', 2: 'c', 3: 'd'}

i have list of keys want follows:

l = [0, 1] 

now want create list contains values corresponding these keys , wanted know if there pythonic way using list or dict comprehensions.

i can follows:

[x x in d[0]] 

however, not know how iterate on entries of list in setting. tried:

[x x in d[a] in l] # name 'a' not defined [x x in d[for in l]] # invalid syntax 

you want iterate on l, use for element in l. stuff in dictionary in left-hand side, in value-producing expression:

[d[element] element in l] 

note dictionary mapping consecutive integers starting @ 0 letters isn't efficient; may make list:

num_to_letter = [chr(65 + i) in range(4)] 

this still maps 0 'a', 1 'b', etc, without hashing step.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -