Python | Initialize common value to keys

Sometimes, while working with Python, we can be confronted with an issue in which we need to assign each key of dictionary with a common value. This type of problem in not occasional but can occur many times while programming. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using defaultdict() + lambda

The defaultdict can be initialized using a function which by default assigns each new key with the common key. This is most recommended way to perform this task.



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

The original dictionary is : {}
The value of key is :  4

 

Method #2 : Using get() + default value

This method is just a display hack to perform this task. It doesn’t create the actual list, but just prints the default value passed to get function and hence the result.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

The original dictionary is : {}
The value of key is :  4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.