对字典理解的一个小补充

A Small Addition to a Dict Comprehension

我最近一直在试验 Python,并且刚刚发现了 Dict Comprehensions 的强大功能。我在 Python 的参考资料库中阅读了一些关于它们的内容。这是我在他们身上找到的例子:

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

对于我的迷你项目,我有这个代码:

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

但是,我希望计数器在每个循环中递增 1,因此我尝试依靠一些有根据的猜测,如下所示:

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

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

等,但我的 none 猜测奏效了。

这是想要的 I/O:

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

我怎样才能实现我的目标?

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