Python|仅使用列表中的键初始化字典
给定一个列表,任务是通过使用给定列表作为键来创建一个只有键的字典。
让我们看看我们可以完成这项任务的不同方法。
方法#1 :通过迭代列表
# Python code to initialize a dictionary
# with only keys from a list
# List of keys
keyList = ["Paras", "Jain", "Cyware"]
# initialize dictionary
d = {}
# iterating through the elements of list
for i in keyList:
d[i] = None
print(d)
输出:
{'Cyware': None, 'Paras': None, 'Jain': None}
方法#2:使用字典理解
# Python code to initialize a dictionary
# with only keys from a list
# List of Keys
keyList = ["Paras", "Jain", "Cyware"]
# Using Dictionary comprehension
myDict = {key: None for key in keyList}
print(myDict)
输出:
{'Paras': None, 'Jain': None, 'Cyware': None}
方法#3:使用 zip()函数
# Python code to initialize a dictionary
# with only keys from a list
# List of keys
listKeys = ["Paras", "Jain", "Cyware"]
# using zip() function to create a dictionary
# with keys and same length None value
dct = dict(zip(listKeys, [None]*len(listKeys)))
# print dict
print(dct)
输出:
{'Cyware': None, 'Paras': None, 'Jain': None}
方法 #4:使用 fromkeys() 方法
# Python code to initialize a dictionary
# with only keys from a list
# List of keys
Student = ["Paras", "Jain", "Cyware"]
# using fromkeys() method
StudentDict = dict.fromkeys(Student, None)
# printing dictionary
print(StudentDict)
输出:
{'Cyware': None, 'Jain': None, 'Paras': None}