Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary comprehension example

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
like image 533
stenci Avatar asked Jul 07 '13 16:07

stenci


1 Answers

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'}
like image 154
Bakuriu Avatar answered Oct 10 '22 05:10

Bakuriu