Daniel
Daniel

Reputation: 3597

A Small Addition to a Dict Comprehension

I have been experimenting with Python recently, and have just discovered the power of Dict Comprehensions. I read about them a bit in Python's reference library. Here is the example that I found on them:

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

For my mini project, I have this code:

def dictIt(inputString):
    counter = 0
    output = {counter: n for n in inputString}
    return output

However, I want the counter to increment by 1 every loop, so I tried to rely on sort-of-educated guesses like the following:

def dictIt(inputString):
    counter = -1
    output = {counter++: n for n in inputString}
    return output

and

def dictIt(inputString):
    counter = 0
    output = {counter: n for n in inputString: counter++}
    return output

etc, but none of my guesses worked.

This is the desired I/O:

>>> print dictIt("Hello")
    {0:"H", 1:"e", 2:"l", 3:"l", 4:"o"}

How would I be able to achieve what I am aiming for?

Upvotes: 1

Views: 81

Answers (1)

MK.
MK.

Reputation: 34527

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

Upvotes: 4

Related Questions