Populating a dictionary using for loops (python)

I am trying to create a dictionary that uses my code for loops:

dicts = {} keys = range(4) values = ["Hi", "I", "am", "John"] for i in keys: for x in values: dicts[i] = x print(dicts) 

these outputs:

 {0: 'John', 1: 'John', 2: 'John', 3: 'John'} 

why?

I planned to conclude:

 {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} 

why doesn't he take this path and how do we get it right?

+6
source share
2 answers
 dicts = {} keys = range(4) values = ["Hi", "I", "am", "John"] for i in keys: dicts[i] = values[i] print(dicts) 

alternatively

 In [7]: dict(list(enumerate(values))) Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} 
+7
source
 >>> dict(zip(keys, values)) {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} 
+4
source

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


All Articles