Populating a dictionary using for loops (python)

PythonDictionary

Python Problem Overview


I'm trying to create a dictionary using for loops. Here is my code:

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

This outputs:

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

Why?

I was planning on making it output:

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

Why doesn't it output that way and how do we make it output correctly?

Python Solutions


Solution 1 - Python

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'}

Solution 2 - Python

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHalcyon Abraham RamirezView Question on Stackoverflow
Solution 1 - PythonAjayView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow