scripter
scripter

Reputation: 356

Python dictionary comprehension takes only last item in list for value

This is what I'm trying:

d = {num1 : num2 for num1 in range(4) for num2 in range(4,8)}

I thought I should get {0 : 4, 1 : 5, 2 : 6, 3 : 7}

What I get tho is {0 : 7, 1 : 7, 2 : 7, 3 : 7}

Upvotes: 3

Views: 1096

Answers (3)

Coder 477
Coder 477

Reputation: 435

a= dict(zip(range(m), range(m,n)))
print a

This worked for me. In you case it will be

a= dict(zip(range(4), range(4,8)))

Upvotes: 2

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

Nested comprehensions work as if the for loops were nested from top to bottom. Thus, your code is equivalent to -

d = {}
for num1 in range(4):
    for num2 in range(4,8):
        d[num1] = num2

Your dict gets updated with the latest value with each iteration, hence you get 7 in the end. You probably want what @Fernando has answered, i.e.

d = dict(zip(range(4), range(4,8)))

Upvotes: 1

Fernando Cezar
Fernando Cezar

Reputation: 848

If you want to iterate both ranges together, you should do it using zip:

d = {num1 : num2 for num1, num2 in zip(range(4), range(4,8))}

Upvotes: 5

Related Questions