Understanding python dict with two ranges

I am trying to create code that creates, 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 this?

thanks

+4
source share
4 answers

Using zip :

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

Using dict understanding :

 >>> {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 is not working:

Your code is similar to the 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`. 
+6
source
 {i: j for i, j in zip(range(1, 5), range(7, 11))} 
+3
source

Using zip (or itertools.izip ) and itertools.count :

 >>> from itertools import count, izip 

Dict comprehension:

 >>> {k:v for k,v in izip(xrange(1,5), count(7))} {1: 7, 2: 8, 3: 9, 4: 10} 

dict() :

 >>> dict(izip(xrange(1,5), count(7))) {1: 7, 2: 8, 3: 9, 4: 10} 
+2
source

I would use enumerate :

 >>> dict(enumerate(range(7, 11), 1)) {1: 7, 2: 8, 3: 9, 4: 10} 
+2
source

Source: https://habr.com/ru/post/1502072/


All Articles