python - iterate inside a dictionary comprehension statement -


i,m started learning python, i'm sure many things don't know may quite simple solve. however, searching through lot of questions couldn't find answer one.

is possible iterate variable in dictionary comprehension statement?

while searching answer i've found this:

{ _key : _value(_key) _key in _container } 

wich, i'm aware, way of looping inside comprehension, work me, need able iterate value each '_key' in '_container'.

for basic example:

alphabet = 'abcdefghijklmnopqrstuvwxyz'  x = 1  alpha_numbers = {char : x char in alphabet} 

i 'x' 'x += 1' each 'char' in 'alphabet' container. every way try iterate it, inside dictionary comprehension, returns 'invalid syntax' error.

so, possible it? or there better way make it?

thanks in advance.

you can use dict , enumeratepassing x starting value:

alphabet = 'abcdefghijklmnopqrstuvwxyz'  dct = dict(enumerate(alpahbet, x)) # start=x i.e 1 

demo:

in [43]: print dict(enumerate(alphabet,1)) {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'} 

or using enumerate dict comp:

 dct = {i:k i,k in enumerate(alphabet,x)} 

to letters keys reverse order of , k:

dct = {k:i i,k in enumerate(alphabet,x)} 

or using itertools.count dict , zip:

from itertools import count dct = dict(zip(alphabet, count(x))) 

or range, len , zip:

 dct = dict(zip(alphabet, range(x, len(alphabet)+x))) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -