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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :



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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

Dictionary after Initializing multiple key-value : {‘gfg’: 4, ‘is’: 4, ‘best’: 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.