寫一個 Python 程序,用一個實例將兩個列表映射成一個字典。
將兩個列表映射到字典中的 Python 程序示例 1
在這個 python 程序中,我們使用進行循環,並帶有 zip 功能。
# Python Program to Map two lists into a Dictionary
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)
Python 將兩個列表映射到字典輸出中
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
>>>
將兩個列表映射到字典中的程序示例 3
這個 Python 將兩個列表映射到一個字典中的代碼與上面相同。然而,在這個 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}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254291.html