Open In App

Python | Dictionary initialization with common dictionary

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. 

Method 1: Using zip() + repeat() The combination of these functions can be used to perform this particular task. In this, the Dictionary value is attached to the keys repeated using the repeat() by help of zip() 

Step-by-step approach :

  • Import the repeat function from the itertools module.
  • Initialize a dictionary test_dict with key-value pairs.
  • Call the zip() function with two arguments:
    a. The range() function to create a sequence of numbers from 0 to 3 (inclusive).
    b. The repeat() function with the test_dict dictionary as its argument to create an iterable that returns test_dict infinitely.
  • Pass the output of zip() to the dict() function to create a dictionary from the key-value pairs generated by zip().
  • Assign the resulting dictionary to the variable res.
  • Print the resulting dictionary res.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Dictionary initialization with common dictionary
# Using zip() + repeat()
from itertools import repeat
 
# initialization Dictionary
test_dict = {'gfg' : 1, 'best' : 3}
 
# Using zip() + repeat()
# Dictionary initialization with common dictionary
res = dict(zip(range(4), repeat(test_dict)))
 
# printing result
print("The dictionary with record values : " + str(res))


Output

The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3: {'gfg': 1, 'best': 3}}

Time complexity: O(1)
Auxiliary space: O(1)

Method 2: Using dict.fromkeys()

Step-by-step approach:

  • Uses the ‘dict.fromkeys()’ method to initialize a new dictionary named ‘res’. The ‘range(4)’ function creates a sequence of numbers from 0 to 3, and the ‘test_dict’ dictionary is passed as the second argument to the ‘dict.fromkeys()’ method. This creates a new dictionary where each key in the range sequence maps to the same value (which is the entire ‘test_dict’ dictionary).
  • Finally, prints the resulting dictionary using the ‘print()’ function. The resulting dictionary is stored in the ‘res’ variable, and it contains 4 key-value pairs, where each key is a number from 0 to 3, and each value is the same dictionary as ‘test_dict’.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Dictionary initialization with common dictionary
# Using dict.fromkeys()
 
# initialization Dictionary
test_dict = {'gfg' : 1, 'best' : 3}
 
# Using dict.fromkeys()
# Dictionary initialization with common dictionary
res = dict.fromkeys(range(4), test_dict)
 
# printing result
print("The dictionary with record values : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3: {'gfg': 1, 'best': 3}}

Time Complexity : O(n)
Auxiliary Space : O(n)

Method #3: Using a dictionary comprehension. 

Initializes a dictionary named ‘test_dict’ with two key-value pairs. It then creates a new dictionary ‘res’ with keys ranging from 0 to 3, and assigns the same dictionary object ‘test_dict’ as the value for each key. Finally, it prints the resulting dictionary ‘res’.

Python3




test_dict = {'gfg': 1, 'best': 3}
 
res = {key: test_dict for key in range(4)}
 
print("The dictionary with record values : " + str(res))


Output

The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3: {'gfg': 1, 'best': 3}}

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 range provided (which is 4 in this case). 

Method 4: Use a for loop and add key-value pairs to the dictionary

The program initializes an empty dictionary called res. It then enters a loop that iterates four times and on each iteration, it assigns the value of test_dict to the dictionary with key i. Finally, the program prints the resulting dictionary res as a string.

In summary:

  1. Initialize an empty dictionary res.
  2. Loop four times and on each iteration, assign the value of test_dict to the dictionary with key I.
  3. Print the resulting dictionary res as a string.

Python3




test_dict = {'gfg': 1, 'best': 3}
res = {}
for i in range(4):
    res[i] = test_dict
print("The dictionary with record values : " + str(res))


Output

The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3: {'gfg': 1, 'best': 3}}

Time complexity: O(n), where n is the number of iterations in the for loop. 
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary. repetitions is increased, the space complexity

Method 5: Using the dict() constructor and a generator expression:

In this method, we pass a generator expression to the dict() constructor. The generator expression creates a sequence of (key, value) pairs where each key is a number from 0 to 3, and each value is the test_dict dictionary. The dict() constructor converts this sequence of pairs into a dictionary. This method is similar to using a dictionary comprehension, but with the added benefit of being able to use a generator expression to conserve memory.

  • Use the dict() constructor and a generator expression to create a new dictionary called res. The generator expression is (i, test_dict) for i in range(4), which creates a sequence of (key, value) pairs. In this case, the keys are the numbers from 0 to 3, and the values are the entire test_dict dictionary.
  • The dict() constructor takes this sequence of (key, value) pairs and converts it into a dictionary. The resulting dictionary has four keys (0, 1, 2, and 3) and each key has the same value, which is the test_dict dictionary.
  • Finally, print the resulting dictionary res using the print() function and a formatted string. The str() function is used to convert the dictionary to a string so that it can be concatenated with the rest of the string.

Python3




# initialization Dictionary
test_dict = {'gfg': 1, 'best': 3}
 
# Using dict() constructor and a generator expression
# Dictionary initialization with common dictionary
res = dict((i, test_dict) for i in range(4))
 
# printing result
print("The dictionary with record values : " + str(res))


Output

The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3: {'gfg': 1, 'best': 3}}

Time complexity: O(n), where n is the number of keys in the resulting dictionary. 
Auxiliary space: O(n), as we need to store the resulting dictionary in memory.

Method 6: Using the copy() method

This method creates an empty dictionary res, and then uses a for loop to create a new key-value pair in res for each integer in the range 0 to 3. The value associated with each key is a copy of the dictionary test_dict using the copy() method. This creates a new dictionary with the same key-value pairs as test_dict, but any changes made to the new dictionary will not affect the original test_dict.

Step-by-step approach:

  • Define a dictionary called test_dict with two key-value pairs.
  • Create an empty dictionary called res.
  • Use a for loop to iterate over the range of integers from 0 to 3:
    a. For each integer i in the range, create a new key-value pair in res where the key is i and the value is a copy of test_dict.
  • Print the resulting dictionary res as a string.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Dictionary initialization with common dictionary
# Using the copy() method
 
# initialization Dictionary
test_dict = {'gfg' : 1, 'best' : 3}
 
# Using the copy() method
# Dictionary initialization with common dictionary
res = {}
for i in range(4):
    res[i] = test_dict.copy()
 
# printing result
print("The dictionary with record values : " + str(res))


Output

The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3: {'gfg': 1, 'best': 3}}

Time complexity: O(n), where n is the number of key-value pairs in the original dictionary test_dict.
Auxiliary space: O(n), where n is the number of key-value pairs in the original dictionary test_dict. 



Similar Reads

Python - Custom dictionary initialization in list
While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom 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 {dict} + "*" operator This task can be performed using the “*” operato
3 min read
Python - Incremental value initialization in Dictionary
The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index incremental with K difference. Let’s discuss certain ways in which t
5 min read
Counters in Python | Set 1 (Initialization and Updation)
The counter is a container included in the collections module. Now you all must be wondering what is a container. Don't worry first let's discuss the container. What is Container?Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built-in containers are Tuples, lists, and
3 min read
Python - Incremental K sized Row Matrix Initialization
Sometimes, while working with Python, we can have a problem in which we need to perform initialization of matrix with Incremental numbers. This kind of application can come in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing This task can be performed in brute way using loop.
6 min read
Python | Boolean list initialization
Many times in programming, we require to initialize a list with some initial values. In Dynamic programming, this is used more often and mostly the requirement is to initialize with a boolean 0 or 1. Let's discuss certain ways in which this can be achieved. Method #1: Using list comprehension This can easily be done with the naive method, hence, ca
4 min read
Python | List Initialization with alternate 0s and 1s
The initialization of a list with a single number is a generic problem whose solution has been dealt with many times. But sometimes we require to initialize the list with elements alternatively repeating K no. of times. This has use cases in M.L. or A. I algorithms that require presetting of data in lists. Let's discuss certain ways in which this p
6 min read
Python | Interval Initialization in list
There are numerous ways to initialize the list with the elements, but sometimes, its required to initialize the lists with the numbers in a sliced way. This can be custom and hence knowledge of this can come handy. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + enumerate() The list comprehension can do
5 min read
Python - K Matrix Initialization
Sometimes in the world of competitive programming, we need to initialise the matrix, but we don’t wish to do it in a longer way using a loop. We need a shorthand for this. This type of problem is quite common in dynamic programming domain. Let’s discuss certain ways in which this can be done. Method #1: Using List comprehension List comprehension c
5 min read
Python - Incremental Range Initialization in Matrix
Sometimes, while working with Python, we can have a problem in which we need to perform the initialization of Matrix. Simpler initialization is easier. But sometimes, we need to perform range incremental initialization. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is brute way in which this task can be
4 min read
Kaiming Initialization in Deep Learning
Kaiming Initialization is a weight initialization technique in deep learning that adjusts the initial weights of neural network layers to facilitate efficient training by addressing the vanishing or exploding gradient problem. The article aims to explore the fundamentals of Kaiming initialization and it's implementation. What is Kaiming Initializat
7 min read
Practice Tags :