Reputation: 3597
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