首页 > 解决方案 > 如何使用for循环遍历两个列表来创建字典

问题描述

我有两个列表:

num_list = [1,2,3,4]

name_list = ["one","two","three","four"]

我想创建一个带有name_list键和num_list值的新字典。 我知道 zip方法,但我正在尝试使用for循环来进行自己的学习。我尝试过的是:

new={}
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
for i in (name_list):
    for j in (num_list):
        new[i]=j

输出为:

{'one': 4, 'two': 4, 'three': 4, 'four': 4}

谁能解释我在哪里做错了??

标签: python-3.xdictionary

解决方案


您正在使用嵌套的 for 循环。对于每个iinname_list和每个j in num_list,您都在 dictionary 中添加一个元素new。因此,最后,您将 4*4 = 16, key, value 对添加到字典中。

你可以这样做:

new={}
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
for i in range(len(name_list)):
    new[name_list[i]]=num_list[i]

这个问题类似于https://stackoverflow.com/a/15709950/8630546


推荐阅读