Python | Initialize dictionary with multiple keys
Sometimes, while working with dictionaries, we might have a problem in which we need to initialize the dictionary with more than one keys with same value. This application requirement can be in domains of web development in which we might want to declare and initialize at the same time. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop
We can have a loop which performs this particular task. But this just partially solves our problem of multiple addition but the dictionary has to be declared beforehand for this.
# Python3 code to demonstrate working of # Initialize dictionary with multiple keys # Using loop # declare dictionary test_dict = {} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Initialize keys test_keys = ['gfg', 'is', 'best'] # Using loop # Initialize dictionary with multiple keys for keys in test_keys: test_dict[keys] = 4 # printing result print("Dictionary after updating multiple key-value : " + str(test_dict)) |
The original dictionary : {}
Dictionary after updating multiple key-value : {‘is’: 4, ‘gfg’: 4, ‘best’: 4}
Method #2 : Using fromkeys()
This function is used to actually perform both task of multiple assignment and declaration with a single statement. We also use * operator to pack the values together into a dictionary.
# Python3 code to demonstrate working of # Initialize dictionary with multiple keys # Using fromkeys() # Initialize keys test_keys = ['gfg', 'is', 'best'] # Using fromkeys() # Initialize dictionary with multiple keys res ={ **dict.fromkeys(test_keys, 4)} # printing result print("Dictionary after Initializing multiple key-value : " + str(res)) |
Dictionary after Initializing multiple key-value : {‘gfg’: 4, ‘is’: 4, ‘best’: 4}
Recommended Posts:
- Python | Initialize a dictionary with only keys from a list
- Python dictionary with keys having multiple inputs
- Python | Remove multiple keys from dictionary
- Python | Check if given multiple keys exist in a dictionary
- Python | Initialize common value to keys
- Python | Initialize dictionary with None values
- Python | Initialize dictionary with common value
- Python | Add new keys to a dictionary
- Python Dictionary | keys() method
- Python | Minimum value keys in Dictionary
- Python | Get all tuple keys from dictionary
- Python | Get total keys in dictionary
- Python | Add keys to nested dictionary
- Python | Grouping dictionary keys by value
- Python | Get the number of keys with given value N 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.



