Python|用公共值初始化字典
在使用Python时,有时我们可能会遇到需要将静态列表初始化为具有常量值的字典的问题。让我们讨论可以执行此任务的某些方式。
方法 #1:使用dict()
+ 列表理解
上述功能的组合可用于执行此特定任务。在这里,我们只是将从列表中提取的元素转换为键,并使用列表理解和dict().
# Python3 code to demonstrate working of
# Initialize dictionary with common value
# Using list comprehension + dict()
# Initialize list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# Initialize dictionary with common value
# Using list comprehension + dict()
res = dict((sub, 4) for sub in test_list)
# printing result
print("The constructed dictionary with common value : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
The constructed dictionary with common value : {'is': 4, 'gfg': 4, 'best': 4}
方法 #2:使用fromkeys()
fromkeys() 的内置函数也可用于执行此特定任务,该任务用于执行此特定任务本身,并且是执行此任务的更 Pythonic 方式。
# Python3 code to demonstrate working of
# Initialize dictionary with common value
# Using fromkeys()
# Initialize list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# Initialize dictionary with common value
# Using fromkeys()
res = dict.fromkeys(test_list, 4)
# printing result
print("The constructed dictionary with common value : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
The constructed dictionary with common value : {'is': 4, 'gfg': 4, 'best': 4}