Open In App

Python | Initialize common value to keys

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

Sometimes, while working with Python, we can be confronted with an issue in which we need to assign each key of dictionary with a common value. This type of problem is not occasional but can occur many times while programming. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using defaultdict() + lambda The defaultdict can be initialized using a function which by default assigns each new key with the common key. This is most recommended way to perform this task. 

Python3




# Python3 code to demonstrate working of
# Initialize common value to keys
# Using defaultdict()
from collections import defaultdict
 
# Initialize dictionary
test_dict = dict()
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize common value to keys
# Using defaultdict()
res = defaultdict(lambda: 4, test_dict)
res_demo = res['Geeks']
 
# printing result
print("The value of key is :  " + str(res_demo))


Output : 

The original dictionary is : {}
The value of key is :  4

Time Complexity: O(1)
Space Complexity: O(n) -> where n is the number of elements in the dictionary

  Method #2 : Using get() + default value This method is just a display hack to perform this task. It doesn’t create the actual list, but just prints the default value passed to get function and hence the result. 

Python3




# Python3 code to demonstrate working of
# Initialize common value to keys
# Using get() + default value
 
# Initialize dictionary
test_dict = dict()
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize common value to keys
# Using get() + default value
res_demo = test_dict.get('Geeks', 4)
 
# printing result
print("The value of key is :  " + str(res_demo))


Output : 

The original dictionary is : {}
The value of key is :  4

Time Complexity: O(1)
Space Complexity: O(n) -> where n is the number of elements in the dictionary

Method #3: Using a loop to assign the common value to keys

Step-by-step approach to understanding the code you provided:

  1. Initializes an empty dictionary named ‘test_dict‘.
  2. Print the original dictionary using the ‘print()’ function and converts the dictionary to a string using the ‘str()’ function.
  3. Initializes a variable named ‘common_value’ to 4.
  4. Iterate a for loop that iterates over the list [‘Geeks’, ‘for’, ‘Geeks’]. Inside the for loop, the current key in the iteration is used to assign the ‘common_value’ to the key in the ‘test_dict’ dictionary using the key-value assignment syntax.
  5. After the for loop finishes, the dictionary ‘test_dict’ will have three key-value pairs, where each key is ‘Geeks’ and the value is 4.
  6. Now, accesses the key ‘Geeks’ in the dictionary using the indexing operator, and assigns the resulting value to the variable ‘res_demo’.
  7. Print the value of ‘res_demo’ using the ‘print()’ function and converts the value to a string using the ‘str()’ function.

Below is the implementation of the above approach:

Python3




# Initialize dictionary
test_dict = {}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# Initialize common value to keys using a loop
common_value = 4
for key in ['Geeks', 'for', 'Geeks']:
    test_dict[key] = common_value
 
# Access a key that we set a common value for
res_demo = test_dict['Geeks']
 
# printing result
print("The value of key is: " + str(res_demo))


Output

The original dictionary is: {}
The value of key is: 4

This method will have a time complexity of O(n), where n is the number of keys in the dictionar= because we need to iterate over each key to assign the common value. 

The space complexity is also O(n), because we are storing n key-value pairs in the dictionary.



Similar Reads

Python | Initialize dictionary with common value
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
5 min read
Python | Initialize a dictionary with only keys from a list
Given a List, the task is to create a dictionary with only keys by using given list as keys. Let's see the different methods we can do this task. Method #1 : By iterating through list C/C++ Code # Python code to initialize a dictionary # with only keys from a list # List of keys keyList = ["Paras", "Jain", "Cyware"] #
4 min read
Python | Initialize dictionary with multiple keys
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 performe
8 min read
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 performed. Method #1 : Using list comprehension This is
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 Python dictionaries with keys and values, accompan
3 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. Let’s discuss certain ways to achieve this partic
4 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python | Combine two dictionary adding values for common keys
Given two dictionaries, the task is to combine the dictionaries such that we get the added values for common keys in the resultant dictionary. Example: Input: dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} Output: {'for': 325, 'Geeks': 100, 'geek': 200} Let's see some of the methods on How to Combine two dictio
4 min read
Python - Common keys in list and dictionary
Given a dictionary and list, extract all the keys and list which are common. Input : test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}, test_list = ["Gfg", "best", "CS"] Output : ['Gfg', 'best'] Explanation : Gfg and best are present in both dictionary and List. Input : test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "gee
8 min read
Practice Tags :