Sometimes, while working with dictionaries, we might have a problem in which we need to initialize the dictionary with more than one key with the same value. This application requirement can be in domains of web development in which we might want to declare and initialize simultaneously. Let’s discuss certain ways in which this task can be performed.
Method #1: Using loop
We can have a loop that performs this particular task. But this just partially solves our problem of multiple additions but the dictionary has to be declared beforehand for this.
Python3
# 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 : {'gfg': 4, 'is': 4, 'best': 4}
Time complexity: O(n), where n is the number of keys in the test_keys list.
Auxiliary space: O(n), where n is the number of keys in the test_keys list.
Method #2: Using fromkeys()
This function is used to actually perform both tasks of multiple assignments and declarations with a single statement. We also use * operator to pack the values together into a dictionary.
Python3
# 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}
Time complexity: O(n), where n is the length of the test_keys list.
Auxiliary space: O(n), as we are creating a dictionary with n key-value pairs.
Method #3: Use repeat() function
This is another way to initialize a dictionary with multiple keys using the repeat() function.
Python3
# Python3 code to demonstrate working of # Initialize dictionary with multiple keys # Using repeat() # import repeat from itertools from itertools import repeat # Initialize keys test_keys = [ 'gfg' , 'is' , 'best' ] # Using repeat() # Initialize dictionary with multiple keys res = {k: v for k, v in zip (test_keys, repeat( 4 ))} # printing result print ( "Dictionary after updating multiple key-value : " + str (res)) # This code is contributed by Edula Vinay Kumar Reddy |
Dictionary after updating multiple key-value : {'gfg': 4, 'is': 4, 'best': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using dictionary comprehension:
Approach:
- Initialize a list of keys test_keys with three elements ‘gfg’, ‘is’, and ‘best’.
- Use dictionary comprehension to create a dictionary res with keys as the elements in test_keys and values as 4.
- Print the result of the dictionary res after updating the values.
Below is the implementation of the above approach:
Python3
# Initialize keys test_keys = [ 'gfg' , 'is' , 'best' ] # Using dictionary comprehension # Initialize dictionary with multiple keys res = {k: 4 for k in test_keys} # printing result print ( "Dictionary after updating multiple key-value : " + str (res)) |
Dictionary after updating multiple key-value : {'gfg': 4, 'is': 4, 'best': 4}
Time complexity: O(n), where n is the number of keys in the dictionary
Auxiliary space: O(n), where n is the number of keys in the dictionary. This is because we need to store the dictionary in memory.
Method #5: Using dict.fromkeys() method
- Create an empty dictionary test_dict using {}.
- Initialize a list test_keys with the keys you want to add to the dictionary.
- Use the dict.fromkeys() method to create a dictionary with the keys from test_keys and a default value of 4. Assign the resulting dictionary to test_dict.
- Print the updated dictionary.
Python3
# Python3 code to demonstrate working of # Initialize dictionary with multiple keys # Using dict.fromkeys() # create empty dictionary test_dict = {} # printing original dictionary print ( "The original dictionary : " + str (test_dict)) # Initialize keys test_keys = [ 'gfg' , 'is' , 'best' ] # Using dict.fromkeys() # Initialize dictionary with multiple keys test_dict = dict .fromkeys(test_keys, 4 ) # printing result print ( "Dictionary after updating multiple key-value : " + str (test_dict)) |
The original dictionary : {} Dictionary after updating multiple key-value : {'gfg': 4, 'is': 4, 'best': 4}
Time complexity: O(n), where n is the number of keys in test_keys.
Auxiliary space: O(n), where n is the number of keys in test_keys.
Method #6: Using zip() function and dictionary comprehension:
Algorithms:
- Create a list of keys to be used to initialize the dictionary.
- Create a list of default values that will be used for each key.
- Use the zip() function to combine the keys and default values into a list of tuples.
- Use dictionary comprehension to convert the list of tuples into a dictionary.
- Print the original Dictionary and the updated dictionary.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of # Initialize dictionary with multiple keys # Using zip() function and dictionary # comprehension # Create a list of keys keys = [ 'gfg' , 'is' , 'best' ] # Create a list of default values default_values = [ 4 ] * len (keys) # Combine the keys and default values # into a list of tuples key_value_pairs = list ( zip (keys, default_values)) # Use dictionary comprehension to convert # the list of tuples into a dictionary test_dict = {k: v for k, v in key_value_pairs} # Print the updated dictionary print ( "Dictionary after updating multiple key-value : " + str (test_dict)) |
Dictionary after updating multiple key-value : {'gfg': 4, 'is': 4, 'best': 4}
Time Complexity: O(N), where N is the number of keys in the dictionary.
Auxiliary Space: O(N), where N is the number of keys in the dictionary.
Method#7: Using the Recursive method:
In this implementation, the function init_dict takes a list of keys and a value as input and returns a new dictionary where each key in keys is associated with the same value.
The implementation uses recursion to build the dictionary. The base case is when key is empty, in which case the function returns an empty dictionary. Otherwise, the function creates a dictionary with a single key-value pair as {keys[0]: value} and then calls itself recursively with the remaining keys keys[1:]. The result of the recursive call is merged with the current key-value pair using the unpacking operator ** to create a new dictionary.
Python3
# Python program for the above approach # Function to generate the dictionary # recursively def init_dict(keys, value): if not keys: return {} return {keys[ 0 ]: value, * * init_dict(keys[ 1 :], value)} # Driver Code test_keys = [ 'gfg' , 'is' , 'best' ] test_dict = init_dict(test_keys, 4 ) print ( "Dictionary after updating multiple key-value : " + str (test_dict)) |
Dictionary after updating multiple key-value : {'gfg': 4, 'is': 4, 'best': 4}
Time Complexity: O(n), where n is the length of the keys list. This is because the function needs to create a key-value pair for each key in the list, which takes constant time, and it needs to do this for each key in the list, which takes O(n) time in the worst case.
Space Complexity: O(n), because the recursive function calls itself n times, and each call creates a new dictionary with a single key-value pair. However, note that this is the worst-case space complexity because it assumes that each call to the function creates a new dictionary. In practice, the Python interpreter may optimize the function calls and reuse the same dictionary in memory, reducing the actual space usage.
Method#8: Using heapq:
Algorithm:
- Initialize a list of keys and a value
- Create a list of tuples with keys and value
- Use the nsmallest function from heapq to get the smallest n elements from the tuple list
- Convert the result to a dictionary using the dict() function
- Print the resulting dictionary
Python3
import heapq # initialize list of tuples test_keys = [ 'gfg' , 'is' , 'best' ] test_value = 4 tuple_list = [(key, test_value) for key in test_keys] # convert list of tuples to dictionary using heapq test_dict = dict (heapq.nsmallest( len (tuple_list), tuple_list)) print ( "Dictionary after Initializing multiple key-value : " + str (test_dict)) #This code is contributed by Rayudu. |
Dictionary after Initializing multiple key-value : {'best': 4, 'gfg': 4, 'is': 4}
Time complexity: O(n log n), where n is the number of elements in the list of tuples. The nsmallest function uses a heap to find the smallest n elements, which takes O(n log n) time.
Space complexity: O(n), where n is the number of elements in the list of tuples. The nsmallest function creates a heap of size n. The resulting dictionary also has n key-value pairs.