Python dictionary comprehension example

stenci picture stenci · Jul 7, 2013 · Viewed 9k times · Source

I am trying to learn Python dictionary comprehension, and I think it is possible to do in one line what the following functions do. I wasn't able to make the n+1 as in the first or avoid using range() as in the second.

Is it possible to use a counter that automatically increments during the comprehension, as in test1()?

def test1():
    l = ['a', 'b', 'c', 'd']
    d = {}
    n = 1
    for i in l:
        d[i] = n
        n = n + 1
    return d

def test2():
    l = ['a', 'b', 'c', 'd']
    d = {}
    for n in range(len(l)):
        d[l[n]] = n + 1
    return d

Answer

Bakuriu picture Bakuriu · Jul 7, 2013

It's quite simple using the enumerate function:

>>> L = ['a', 'b', 'c', 'd']
>>> {letter: i for i,letter in enumerate(L, start=1)}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

Note that, if you wanted the inverse mapping, i.e. mapping 1 to a, 2 to b etc, you could simply do:

>>> dict(enumerate(L, start=1))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}