Reputation: 356
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
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
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
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