Python | Initialize dictionary with common value
Last Updated : 27 Apr, 2023
While working with Python, sometimes, we might have a problem in which we require the initialize the static list into a dictionary with a constant value. Let's discuss certain ways in which this task can be performed.
Method #1: Using dict() + list comprehension The combination of above functions can be used to perform this particular task. In this, we just convert the elements extracted from list as keys and assign the common value using list comprehension and conversion done by dict().
Python3 # Python3 code to demonstrate working of # Initialize dictionary with common value # Using list comprehension + dict() # Initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list is : " + str(test_list)) # Initialize dictionary with common value # Using list comprehension + dict() res = dict((sub, 4) for sub in test_list) # printing result print("The constructed dictionary with common value : " + str(res))
Output : The original list is : ['gfg', 'is', 'best'] The constructed dictionary with common value : {'is': 4, 'gfg': 4, 'best': 4}
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using fromkeys() The inbuilt function of fromkeys() can also be used to perform this particular task itself and is more Pythonic way to perform this task.
Python3 # Python3 code to demonstrate working of # Initialize dictionary with common value # Using fromkeys() # Initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list is : " + str(test_list)) # Initialize dictionary with common value # Using fromkeys() res = dict.fromkeys(test_list, 4) # printing result print("The constructed dictionary with common value : " + str(res))
Output : The original list is : ['gfg', 'is', 'best'] The constructed dictionary with common value : {'is': 4, 'gfg': 4, 'best': 4}
Method #3: Use the zip() function with a list comprehension
In this method, the zip() function is used to combine each element of the test_list with the value 4 using a list comprehension. The resulting pairs are then used to create a dictionary.
Python3 test_list = ['gfg', 'is', 'best'] # using zip() function with list comprehension res = dict(zip(test_list, [4] * len(test_list))) # printing result print("The constructed dictionary with common value : " + str(res))
OutputThe constructed dictionary with common value : {'gfg': 4, 'is': 4, 'best': 4}
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), as it creates a new list of length n containing the constant value 4, and a dictionary of length n to store the resulting pair
Method #4: Using defaultdict from collections
Step-by-step approach:
- Import defaultdict from the collections module:
- Initialize list
- Use defaultdict with the common value as the default value to create the dictionary:
- The update() method is used to add the keys from test_list to the defaultdict so that all keys have the common value of 4.
- Print the result
Below is the implementation of the above approach:
Python3 from collections import defaultdict # Initialize list test_list = ['gfg', 'is', 'best'] # Initialize defaultdict with common value res = defaultdict(lambda: 4) res.update({key: 4 for key in test_list}) # Print the result print("The original list is : ", test_list) print("The constructed dictionary with common value : ", dict(res))
OutputThe original list is : ['gfg', 'is', 'best'] The constructed dictionary with common value : {'gfg': 4, 'is': 4, 'best': 4}
Time complexity: O(n) where n is the length of test_list.
Auxiliary space: O(n) to store the dictionary.
Method #5: Using dictionary comprehension:
Step-by-step approach:
- Initializes a list named 'test_list' with three string elements: 'gfg', 'is', and 'best'.
- Prints the original list using the 'print()' function and string concatenation.
- Use a dictionary comprehension to create a new dictionary named 'res'. The dictionary comprehension iterates through each element (sub) in 'test_list' and creates a key-value pair where the key is the current element (sub) and the value is 4.
- Finally, prints the resulting dictionary using the 'print()' function and string concatenation.
Below is the implementation of the above approach:
Python3 # Python3 code to demonstrate working of # Initialize dictionary with common value # Using dictionary comprehension # Initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list is: " + str(test_list)) # Initialize dictionary with common value # Using dictionary comprehension res = {sub: 4 for sub in test_list} # printing result print("The constructed dictionary with common value: " + str(res))
OutputThe original list is: ['gfg', 'is', 'best'] The constructed dictionary with common value: {'gfg': 4, 'is': 4, 'best': 4}
Time complexity: O(n), where n is the number of elements in the list. The dictionary comprehension iterates through each element in the list once.
Auxiliary space: O(n), where n is the number of elements in the list. The dictionary created has n key-value pairs, where n is the length of the list.
Similar Reads
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
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 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 - Dictionary with Index as Value
We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}. Using Dictionary ComprehensionWe can use dictionary comprehen
2 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Letâs discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops
10 min read
Python | Dictionary initialization with common dictionary
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 whi
7 min read
Python | Initializing dictionary with list index-values
While working with Python we might need to perform tasks in which we need to assign a dictionary with list values as dictionary values and index as dictionary keys. This type of problem is quite common in cases we need to perform data-type conversion. Let's discuss certain ways in which this task ca
4 min read
Python | Initializing dictionary with list index values
While working with dictionaries, we might come across a problem in which we require to attach each value in list with it's index, to be used afterwards to solve question. This technique is usually very useful in competitive programming domain. Let's discuss certain ways in which this task can be per
5 min read
Initialize Dictionary with Default Values
Python is a simple and versatile language that uses dictionaries to manage data efficiently. Dictionaries are like containers that store information in pairs, making it easy to organize and find things. As programs become more complicated, dealing with missing information in dictionaries becomes a b
3 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