python - A Small Addition to a Dict Comprehension -


i have been experimenting python recently, , have discovered power of dict comprehensions. read them bit in python's reference library. here example found on them:

>>> {x: x**2 x in (2, 4, 6)}     {2:4, 4:16, 6:36} 

for mini project, have code:

def dictit(inputstring):     counter = 0     output = {counter: n n in inputstring}     return output 

however, want counter increment 1 every loop, tried rely on sort-of-educated guesses following:

def dictit(inputstring):     counter = -1     output = {counter++: n n in inputstring}     return output 

and

def dictit(inputstring):     counter = 0     output = {counter: n n in inputstring: counter++}     return output 

etc, none of guesses worked.

this desired i/o:

>>> print dictit("hello")     {0:"h", 1:"e", 2:"l", 3:"l", 4:"o"} 

how able achieve aiming for?

{i:n i,n in enumerate("hello")} 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -