Python – Alternate Default Key Value
Last Updated :
21 Apr, 2023
Sometimes, while working with Python Dictionaries, we can have problem in which we need to assign a particular value to a particular key, but in absence, require the similar’s key’s value but from different dictionary. This problem can have applications in domain of web development. Let’s discuss certain ways in which this task can be performed.
Input : test_dict = {‘gfg’ : {‘a’ : 1, ‘b’ : 2, ‘c’ : 3}, ‘best’ : {‘a’ : 3, ‘c’ : 4, ‘b’ : 17}} Output : 17 Input : test_dict = {‘gfg’ : {‘b’ : 1}, ‘best’ : {‘a’ : 3}} Output : 1
Method #1 : Using loop This is brute force way in which this task can be performed. In this, we test for a particular dictionary for value, if not present we check the alternate key and assign value.
Python3
test_dict = { 'gfg' : { 'a' : 1 , 'b' : 2 , 'c' : 3 }, 'best' : { 'a' : 3 , 'c' : 4 }}
print ("The original dictionary is : " + str (test_dict))
alt_key = 'gfg'
if 'b' in test_dict[ 'best' ]:
res = test_dict[ 'best' ][ 'b' ]
else :
res = test_dict[alt_key][ 'b' ]
print ("The required value : " + str (res))
|
Output :
The original dictionary is : {‘gfg’: {‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘best’: {‘a’: 3, ‘c’: 4}} The required value : 2
Method #2 : Using get() This task can also be performed using this method. We can exploit the capability of get() to render default values in case of absence of values.
Python3
test_dict = { 'gfg' : { 'a' : 1 , 'b' : 2 , 'c' : 3 }, 'best' : { 'a' : 3 , 'c' : 4 }}
print ("The original dictionary is : " + str (test_dict))
alt_key = 'gfg'
res = test_dict.get( 'best' ).get( 'b' , test_dict.get(alt_key)[ 'b' ])
print ("The required value : " + str (res))
|
Output :
The original dictionary is : {‘gfg’: {‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘best’: {‘a’: 3, ‘c’: 4}} The required value : 2
Method #3 : Using list comprehension and min()
Approach
we use a list comprehension to extract the values of the key ‘b’ from each dictionary in the dictionary values. We then use the min() function to get the minimum value, which is the required default value.
Algorithm
1. Use a list comprehension to extract the values of the key ‘b’ from each dictionary in the dictionary values.
2. Use the filter() function to remove None values from the list.
3. Use the min() function to get the minimum value, which is the required default value.
Python3
def get_default_value(test_dict):
values = [d.get( 'b' ) for d in test_dict.values()]
values = list ( filter ( None , values))
default_value = min (values) if values else None
return default_value
test_dict = { 'gfg' : { 'a' : 1 , 'b' : 2 , 'c' : 3 }, 'best' : { 'a' : 3 , 'c' : 4 , 'b' : 17 }}
print (get_default_value(test_dict))
|
Time Complexity: O(n) – iterating through the values of the dictionary takes n time complexity.
Space Complexity: O(n) – creating a list to store the extracted values of the key ‘b’.
METHOD 4: Using defaultdict
APPROACH:
The approach taken in this code is to use a defaultdict of defaultdicts to create a new dictionary with the desired default value for a particular key in all nested dictionaries. First, a defaultdict of defaultdicts is initialized, with the default value set to the desired default value. Then, for each key-value pair in the original dictionary, the value (which is a nested dictionary) is updated into the new defaultdict. Since the defaultdicts are used, any missing keys in the nested dictionary will be automatically populated with the default value.
ALGORITHM:
1.Initialize a defaultdict of defaultdicts with the desired default value
2.For each key-value pair in the original dictionary:
a. Update the nested dictionary into the new defaultdict
3.Return the new defaultdict
Python3
from collections import defaultdict
def set_default(dictionary, key, default):
nested_dict = defaultdict( lambda : defaultdict( lambda : default))
for k, v in dictionary.items():
nested_dict[k].update(v)
return nested_dict[key][key]
original_dict = { 'gfg' : { 'a' : 1 , 'b' : 2 , 'c' : 3 }, 'best' : { 'a' : 3 , 'c' : 4 }}
required_value = 2
result = set_default(original_dict, 'b' , required_value)
print (result)
|
Time complexity: O(n*m), where n is the number of key-value pairs in the original dictionary and m is the average number of key-value pairs in each nested dictionary.
Auxiliary Space: O(n*m), since the new defaultdict of defaultdicts will contain the same number of key-value pairs as the original dictionary.
METHOD 5: Using reduce():
Algorithm:
- Initialize nested_dict to the input dictionary.
- Iterate over the characters in the input key using reduce.
- At each iteration, set the value of nested_dict for the current character to a new default dictionary with the default value.
- Return the value of the required key from the nested_dict.
Python3
from functools import reduce
from collections import defaultdict
def set_default(dictionary, key, default):
nested_dict = reduce ( lambda d, k: d.setdefault(k, defaultdict( lambda : default)), key, dictionary)
return nested_dict[key]
original_dict = { 'gfg' : { 'a' : 1 , 'b' : 2 , 'c' : 3 }, 'best' : { 'a' : 3 , 'c' : 4 }}
print ( "The original dictionary is : " + str (original_dict))
required_value = 2
res = set_default(original_dict, 'b' , required_value)
print ( "The required value : " + str (res))
|
Output
The original dictionary is : {'gfg': {'a': 1, 'b': 2, 'c': 3}, 'best': {'a': 3, 'c': 4}}
The required value : 2
Time Complexity:
The reduce function iterates over each character in the input key, so the time complexity of set_default is O(n), where n is the length of the input key.
The setdefault method on a dictionary has a time complexity of O(1) on average, so the overall time complexity of the function is O(n).
Space Complexity:
The nested_dict dictionary is initially a copy of the input dictionary, so it has the same space complexity as the input, which is O(m), where m is the number of keys in the input dictionary.
The reduce function creates new default dictionaries for each key in the input key, so the maximum depth of the nested_dict dictionary is equal to the length of the input key. Therefore, the space complexity of the function is O(m * k), where k is the length of the input key.
Similar Reads
Python - Alternate list elements as key-value pairs
Given a list, convert it into dictionary by mapping alternate elements as key-value pairs. Input : test_list = [2, 3, 5, 6, 7, 8] Output : {3: 6, 6: 8, 2: 5, 5: 7} Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate] Input : test_list = [2, 3, 5, 6] Output : {3: 6,
2 min read
Python Dict Get Value by Key Default
We are given a dictionary in Python where we store key-value pairs and our task is to retrieve the value associated with a particular key. Sometimes the key may not be present in the dictionary and in such cases we want to return a default value instead of getting an error. For example, if we have a
4 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Get Dictionary Value by Key - Python
We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t
3 min read
Python Dictionary Add Value to Existing Key
The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
2 min read
Python - Filter key's value from other key
Sometimes, while working with Python dictionary, we can have a problem in which we need to extract a value from dictionary list of the key on basis of some other key equality. This kind of problem is common in domains that include data, for e.g web development. Let's discuss certain ways in which th
7 min read
Python Create Dictionary from List with Default Values
Creating a dictionary from a list with default values allows us to map each item in the list to a specific default value. Using dict.fromkeys(), we can quickly create a dictionary where all the keys from the list are assigned a default value, such as None or any other constant. Using dict.fromkeys()
2 min read
Python - Decrement Dictionary value by K
Sometimes, while working with dictionaries, we can have a use-case in which we require to decrement a particular keyâs value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Letâs disc
3 min read
Python - Minimum value key assignment
Given two dictionaries, the task is to write a Python program to assign minimum values for matching keys from both dictionaries. Examples: Input : test_dict1 = {"gfg" : 1, "is" : 7, "best" : 8}, test_dict2 = {"gfg" : 2, "is" : 2, "best" : 10}Output : {"gfg" : 1, "is" : 2, "best" : 8}Explanation : Mi
5 min read
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
2 min read