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 Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read