从列表中填充字典值

时间:2012-07-13 09:46:42

标签: python list dictionary

我正在尝试在python中构建一个字典。代码如下所示:

dicti = {}
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
dicti = dicti.fromkeys(keys)

values = [2, 3, 4, 5, 6, 7, 8, 9]

如何使用列表填充字典值?是否有内置功能?

结果应该是这样的:

dicti = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}

3 个答案:

答案 0 :(得分:21)

如果您有两个列表keys对应 values

keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = dict(zip(keys, values))

dicti现在是{1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9}

答案 1 :(得分:0)

这样可行,但列表必须大小相同(删除键列表中的9)

keys = [1, 2, 3, 4, 5, 6, 7, 8]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = {}

for x in range(len(keys)):
     dicti[keys[x]] = values[x]

答案 2 :(得分:0)

针对您的具体情况的另一名班轮人员是

dicti = {k:v for k, v in enumerate(values, start=1)}

结果是:

print(dicti)
{1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}