Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dict comprehension with two ranges

I'm trying to produce some code that produces for example:

{1:7,2:8,3:9,4:10}

and

{i:j for i in range(1,5) for j in range(7,11)}

produces

{1: 10, 2: 10, 3: 10, 4: 10}

how can I fix it?

thanks

like image 207
Tahnoon Pasha Avatar asked Dec 12 '22 11:12

Tahnoon Pasha


1 Answers

Using zip:

>>> dict(zip(range(1,5), range(7,11)))
{1: 7, 2: 8, 3: 9, 4: 10}

Using dict comprehension:

>>> {k:v for k, v in zip(range(1,5), range(7,11))}
{1: 7, 2: 8, 3: 9, 4: 10}

>>> {x:x+6 for x in range(1,5)}
{1: 7, 2: 8, 3: 9, 4: 10}

Why your code does not work:

Your code is similar to following code:

ret = {}
for i in range(1,5):
    for j in range(7,11):
        ret[i] = j
    # ret[i] = 10 is executed at last for every `i`.
like image 105
falsetru Avatar answered Dec 23 '22 14:12

falsetru