99

I'm trying to create a dictionary using two 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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Halcyon Abraham Ramirez
  • 1,520
  • 1
  • 16
  • 17

2 Answers2

148
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'}
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Ajay
  • 5,267
  • 2
  • 23
  • 30
  • 2
    thank you for your asnwer. thats interesting. because enumerate also gives out numbers right? cool – Halcyon Abraham Ramirez May 16 '15 at 21:32
  • I'm wondering since your answer has more votes, is there a reason one might prefer your alt answer to the dict(zip()) answer below? Is there any real different in runtime, or since zip is a special type of enumerate does it just come down to whether we want the dict.keys to be integers or strings? – pmackni Jan 18 '21 at 16:24
89
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358