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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30280856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:10:23  来源:igfitidea点击:

Populating a dictionary using for loops (python)

pythondictionary

提问by Halcyon Abraham Ramirez

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

我正在尝试使用 for 循环创建字典。这是我的代码:

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?

为什么它不以这种方式输出,我们如何使其正确输出?

采纳答案by Ajay

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

回答by Ignacio Vazquez-Abrams

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