Populating a dictionary using for loops (python)
本问题已经有最佳答案,请猛点这里访问。
我正在尝试创建一个用于循环的字典。这是我的代码:
1 2 3 4 5 6 7 | dicts = {} keys = range(4) values = ["Hi","I","am","John"] for i in keys: for x in values: dicts[i] = x print(dicts) |
此输出:
1 | {0: 'John', 1: 'John', 2: 'John', 3: 'John'} |
为什么?
我计划把它输出出来:
1 | {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} |
为什么它不能以这种方式输出?我们如何使它正确输出?
1 2 3 4 5 6 | dicts = {} keys = range(4) values = ["Hi","I","am","John"] for i in keys: dicts[i] = values[i] print(dicts) |
替代地
1 2 | In [7]: dict(list(enumerate(values))) Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} |
1 2 | >>> dict(zip(keys, values)) {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'} |