Python | Initialize dictionary with multiple keys
Last Updated :
02 May, 2023
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))
OutputThe 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))
OutputDictionary 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
OutputDictionary 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))
OutputDictionary 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))
OutputThe 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))
OutputDictionary 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))
OutputDictionary 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.
OutputDictionary 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.
Similar Reads
Python - Initialize dictionary keys with Matrix
Sometimes, while working with Python Data, we can have a problem in which we need to construct an empty mesh of dictionaries for further population of data. This problem can have applications in many domains which include data manipulation. Let's discuss certain ways in which this task can be perfor
4 min read
Initialize a Dictionary with Only Keys from a List - Python
The task of initializing a dictionary with only keys from a list in Python involves creating a dictionary where the keys are derived from the elements of the list and each key is assigned a default value . For example, given a list like ["A", "B", "C"], the goal is to transform this list into a dict
3 min read
Initialize Python Dictionary with Keys and Values
In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize
3 min read
Python | Initialize list with empty dictionaries
While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it's utility in web development to store records. Let's discuss certain ways in which this task can be performed. Method #1 : Using {} + "*" operator Thi
5 min read
Python | Initialize dictionary with None values
Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
4 min read
Python - Initialize dictionary with custom value list
In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with a custom list.
4 min read
Python - Remove Multiple Keys from Dictionary
We are given a dictionary and our task is to remove multiple keys from the dictionary. For example, consider a dictionary d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} where we want to remove the keys 'b' and 'd', then the output will be {'a': 1, 'c': 3}. Let's explore different methods to remove multiple ke
3 min read
How to Initialize Dictionary in Python
In Python dictionary, each key is unique and we can store different data types as values. The simplest and most efficient method to initialize a dictionary is using curly braces {}. This is the easiest and most common way to create a dictionary. We can use curly braces '{} ' and separate the keys an
2 min read
Python - Assign values to initialized dictionary keys
Sometimes, while working with python dictionaries, we can have a problem in which we need to initialize dictionary keys with values. We save a mesh of keys to be initialized. This usually happens during web development while working with JSON data. Lets discuss certain ways in which this task can be
5 min read
Python Merge Dictionaries with Same Keys
When working with dictionaries in Python, you should understand that they are mutable, unordered collections of key-value pairs. This flexibility allows us to quickly merge dictionaries, but what happens when two dictionaries have the same key? Python allows us to manage this situation. In this arti
3 min read