📜  Python – 使用没有值的列表创建字典

📅  最后修改于: 2022-05-13 01:55:11.752000             🧑  作者: Mango

Python – 使用没有值的列表创建字典

有时您可能需要将列表转换为 dict 对象以获得更好和更快的操作。让我们看看如何将列表转换为无值字典。在这里,我们将找到执行此操作的三种方法。

方法 #1:使用 zip() 和 dict

Python3
# Python code to demonstrate
# converting list into dictionary with none values
# using zip() and dictionary
 
# initializing list
ini_list = [1, 2, 3, 4, 5]
 
# printing initialized list
print ("initial list", str(ini_list))
 
# Converting list into dictionary using zip() and dictionary
res = dict(zip(ini_list, [None]*len(ini_list)))
 
# printing final result
print ("final dictionary", str(res))


Python3
# Python code to demonstrate converting
# list into dictionary with none values
# using dict()
 
# initializing list
ini_list = [1, 2, 3, 4, 5]
 
# printing initialized list
print ("initial list", str(ini_list))
 
# Converting list into dict()
res = dict.fromkeys(ini_list)
 
# printing final result
print ("final dictionary", str(res))


Python3
# Python code to demonstrate converting
# list into dictionary with none values
# using dict comprehension
 
# initializing list
ini_list = [1, 2, 3, 4, 5]
 
# printing initialized list
print ("initial list", str(ini_list))
 
# Converting list into dict()
res = {key: None for key in ini_list}
 
# printing final result
print ("final dictionary", str(res))


输出:
initial list [1, 2, 3, 4, 5]
final dictionary {1: None, 2: None, 3: None, 4: None, 5: None}

方法#2:使用字典

Python3

# Python code to demonstrate converting
# list into dictionary with none values
# using dict()
 
# initializing list
ini_list = [1, 2, 3, 4, 5]
 
# printing initialized list
print ("initial list", str(ini_list))
 
# Converting list into dict()
res = dict.fromkeys(ini_list)
 
# printing final result
print ("final dictionary", str(res))
输出:
initial list [1, 2, 3, 4, 5]
final dictionary {1: None, 2: None, 3: None, 4: None, 5: None}

方法 #3:使用 dict 理解

Python3

# Python code to demonstrate converting
# list into dictionary with none values
# using dict comprehension
 
# initializing list
ini_list = [1, 2, 3, 4, 5]
 
# printing initialized list
print ("initial list", str(ini_list))
 
# Converting list into dict()
res = {key: None for key in ini_list}
 
# printing final result
print ("final dictionary", str(res))
输出:
initial list [1, 2, 3, 4, 5]
final dictionary {1: None, 2: None, 3: None, 4: None, 5: None}