Python|将两个列表转换为字典
在实时应用程序中,数据类型之间的相互转换通常是必要的,因为某些系统具有某些模块,这些模块需要特定数据类型的输入。让我们讨论一个将两个列表转换为key:value
对字典的简单但有用的实用程序。
方法#1:朴素的方法
可用于执行此任务的基本方法是实现此任务的蛮力方法。为此,只需声明一个字典,然后为两个列表运行嵌套循环,并将键和值对分配给从列表值到字典。
# Python3 code to demonstrate
# conversion of lists to dictionary
# using naive method
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
# Printing original keys-value lists
print ("Original key list is : " + str(test_keys))
print ("Original value list is : " + str(test_values))
# using naive method
# to convert lists to dictionary
res = {}
for key in test_keys:
for value in test_values:
res[key] = value
test_values.remove(value)
break
# Printing resultant dictionary
print ("Resultant dictionary is : " + str(res))
输出:
Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Varsha': 5, 'Rash': 1, 'Kil': 4}
方法#2:使用字典理解
实现上述方法的方法越简洁,字典理解方法通过减少输入行数提供了更快、更省时的方法。
# Python3 code to demonstrate
# conversion of lists to dictionary
# using dictionary comprehension
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
# Printing original keys-value lists
print ("Original key list is : " + str(test_keys))
print ("Original value list is : " + str(test_values))
# using dictionary comprehension
# to convert lists to dictionary
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
# Printing resultant dictionary
print ("Resultant dictionary is : " + str(res))
输出:
Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Varsha': 5, 'Kil': 4, 'Rash': 1}
方法#3:使用zip()
执行此任务的大多数 Pythonic 和通用方法是使用zip()
。此函数以键值对的形式将列表元素与相应索引处的其他列表元素配对。
# Python3 code to demonstrate
# conversion of lists to dictionary
# using zip()
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
# Printing original keys-value lists
print ("Original key list is : " + str(test_keys))
print ("Original value list is : " + str(test_values))
# using zip()
# to convert lists to dictionary
res = dict(zip(test_keys, test_values))
# Printing resultant dictionary
print ("Resultant dictionary is : " + str(res))
输出:
Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Kil': 4, 'Rash': 1, 'Varsha': 5}