新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python程序:將兩個列表映射到一個字典中
創(chuàng)新互聯(lián)Python教程:

成都創(chuàng)新互聯(lián)是工信部頒發(fā)資質(zhì)IDC服務器商,為用戶提供優(yōu)質(zhì)的川西大數(shù)據(jù)中心服務
寫一個 Python 程序,用一個實例將兩個列表映射成一個字典。
將兩個列表映射到字典中的 Python 程序示例 1
在這個 python 程序中,我們使用進行循環(huán),并帶有 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 函數(shù)。
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} 新聞標題:Python程序:將兩個列表映射到一個字典中
分享地址:http://www.fisionsoft.com.cn/article/dpjhgde.html


咨詢
建站咨詢
