📜  Python|将公共值初始化为键

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

Python|将公共值初始化为键

有时,在使用Python时,我们可能会遇到需要为字典的每个键分配一个公共值的问题。这种类型的问题不是偶然的,而是在编程时会发生很多次。让我们讨论可以执行此任务的某些方式。

方法 #1:使用defaultdict() + lambda

defaultdict可以使用一个函数来初始化,该函数默认为每个新键分配公共键。这是执行此任务的最推荐方式。

# Python3 code to demonstrate working of
# Initialize common value to keys
# Using defaultdict()
from collections import defaultdict
  
# Initialize dictionary
test_dict = dict()
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Initialize common value to keys
# Using defaultdict()
res = defaultdict(lambda: 4, test_dict)
res_demo = res['Geeks']
  
# printing result
print("The value of key is :  " + str(res_demo))
输出 :
The original dictionary is : {}
The value of key is :  4

方法 #2:使用get() + 默认值

此方法只是执行此任务的显示技巧。它不会创建实际的列表,而只是打印传递给get函数的默认值以及结果。

# Python3 code to demonstrate working of
# Initialize common value to keys
# Using get() + default value
  
# Initialize dictionary
test_dict = dict()
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Initialize common value to keys
# Using get() + default value
res_demo = test_dict.get('Geeks', 4)
  
# printing result
print("The value of key is :  " + str(res_demo))
输出 :
The original dictionary is : {}
The value of key is :  4