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.
# 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
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.
# 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
Recommended Posts:
- Python | Initialize dictionary with multiple keys
- Python | Initialize a dictionary with only keys from a list
- Python | Initialize dictionary with common value
- Python | Combine two dictionary adding values for common keys
- Initialize Matrix in Python
- Python | Initialize dictionary with None values
- Python | Which is faster to initialize lists?
- Python | Ways to initialize list with alphabets
- Python | Initialize list with empty dictionaries
- Python | Add new keys to a dictionary
- Python | Minimum value keys in Dictionary
- Python Dictionary | keys() method
- Python | Add keys to nested dictionary
- Python | Difference in keys of two dictionaries
- Python | Get total keys in dictionary
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.



