在 Python 中将两个列表转换为字典

pythonserver side programmingprogramming更新于 2026/1/22 7:08:17

虽然 Python 列表包含一系列值,但另一方面,字典包含一对称为键值对的值。在本文中,我们将获取两个列表并将它们标记在一起以创建 Python 字典。

使用 for 和 remove

我们创建两个嵌套的 for 循环。在内循环中,将列表之一指定为字典的键,同时继续从外循环的列表中删除值。

示例

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# 给定列表
print("List of K : ", listK)
print("list of V : ", listV)
# 空字典
res = {}
# 转换为字典
for key in listK:
   for value in listV:
      res[key] = value
      listV.remove(value)
      break
print("Dictionary from lists :\n ",res)

输出

运行上述代码得到以下结果 −

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists:\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})

使用 for 和 range

将两个列表组合起来,通过将它们放入 for 循环中来创建一对值。range 和 len 函数用于跟踪元素的数量,直到创建所有键值对。

示例

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# 给定列表
print("List of K : ", listK)
print("list of V : ", listV)
# 转换为字典
res = {listK[i]: listV[i] for i in range(len(listK))}
print("Dictionary from lists :\n ",res)

输出

运行上述代码得到以下结果 −

('K 列表:',['Mon','Tue','Wed'])
('V 列表:',[3, 6, 5])
('来自列表的字典:\n ',{'Wed':5,'Mon':3,'Tue':6})

使用 zip

zip 函数的作用与上述方法类似。它还将两个列表中的元素组合起来,创建键和值对。

示例

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# 给定列表
print("K 列表 : ", listK)
print("V 列表 : ", listV)
# 转换为字典
res = dict(zip(listK, listV))
print("来自列表的字典:\n ",res)

输出

运行上述代码得到以下结果 −

('K 列表:',['Mon','Tue','Wed'])
('V 列表:',[3, 6, 5])
('来自列表的字典:\n ',{'Wed':5,'Mon':3,'Tue':6})

相关文章


有用资源