在 Python 中将两个列表转换为字典
在 Python 中列表包含一系列值,而字典包含两组值,称为键值对。在本文中,我们将采用两个列表并将它们标记在一起以创建一个 Python 字典。
以 for 和 remove 方式
我们将创建两个嵌套 for 循环。在内部循环中将分配一个列表作为字典的键,同时不停地逐个移除外部 for 循环中列表中的值。
示例
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# Empty dictionary
res = {}
# COnvert to dictionary
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]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = {listK[i]: listV[i] for i in range(len(listK))}
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})以 zip 方式
zip 函数执行的操作与上述方法类似。它还将两个列表中的元素组合起来,创建键值对。
示例
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = dict(zip(listK, listV))
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})
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP