编写一个 Python 程序,将两个列表映射到一个字典,并附带实际示例。
Python 程序将两个列表映射到字典 示例 1
在此 Python 程序中,我们使用 for 循环 和 zip 函数。
keys = ['name', 'age', 'job']
values = ['John', 25, 'Developer']
myDict = {k: v for k, v in zip(keys, values)}
print("Dictionary Items : ", myDict)

Python 程序将两个列表插入字典 示例 2
此代码是将列表插入 字典 的另一种方法。在此 Python 程序中,我们使用 dict 关键字和 zip 函数。
keys = ['name', 'age', 'job']
values = ['John', 25, 'Developer']
myDict = dict(zip(keys, values))
print("Dictionary Items : ", myDict)
将两个列表映射到字典的输出
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
>>>
将两个列表映射到字典的程序 示例 3
此将两个列表映射到字典的代码与上面相同。但是,在此 Python 程序中,我们允许用户插入键和值。
keys = []
values = []
num = int(input("Please enter the Number of elements for this Dictionary : "))
print("Integer Values for Keys")
for i in range(0, num):
x = int(input("Enter Key " + str(i + 1) + " = "))
keys.append(x)
print("Integer Values for Values")
for i in range(0, num):
x = int(input("Enter Value " + str(i + 1) + " = "))
values.append(x)
myDict = dict(zip(keys, values))
print("Dictionary Items : ", myDict)
Please enter the Number of elements for this Dictionary : 3
Integer Values for Keys
Enter Key 1 = 2
Enter Key 2 = 4
Enter Key 3 = 6
Integer Values for Values
Enter Value 1 = 50
Enter Value 2 = 100
Enter Value 3 = 150
Dictionary Items : {2: 50, 4: 100, 6: 150}