使用for循环填充字典(python) [英] Populating a dictionary using for loops (python)

查看:1406
本文介绍了使用for循环填充字典(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这将输出:

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

为什么?

我打算将其输出:

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

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

Why doesn't it output that way and how do we make it output correctly?

推荐答案

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

这篇关于使用for循环填充字典(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆