我尝试使用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'}
为什么不以这种方式输出?我们如何正确输出?
答案 0 :(得分:37)
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
或者
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
答案 1 :(得分:16)
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}