使用 for 循环(python)填充字典

我正在尝试使用 for 循环创建一个字典,下面是我的代码:

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

产出:

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

为什么?

我本来打算输出的:

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

为什么不这样输出,我们如何使它输出正确?

380020 次浏览
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'}
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}