Method 4 : Using the built-in map() function and lambda function

Step-by-step approach:

  • Define a lambda function that takes a key-value pair from a dictionary as an argument and returns a tuple with the key and the modified value (reinitialized to K if it’s a list).
  • Use the map() function to apply the lambda function to each key-value pair in the dictionary and create a new dictionary with the modified values.
  • Return the new dictionary.

Python3




def reinitialize_dict(d, K):
    return dict(map(lambda item: (item[0], [K]*len(item[1]) if isinstance(item[1], list) else K), d.items()))
 
# initializing dictionary
test_dict = {'gfg': [4, 6, 7], 'is': 8, 'best': [[4, 5], [8, 9, 20]]}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing K
K = 4
 
# Reinitialize Value lists to K in Dictionary
res = reinitialize_dict(test_dict, K)
 
# printing result
print("The Reinitialized dictionary : " + str(res))


Output

The original dictionary : {'gfg': [4, 6, 7], 'is': 8, 'best': [[4, 5], [8, 9, 20]]}
The Reinitialized dictionary : {'gfg': [4, 4, 4], 'is': 4, 'best': [4, 4]}

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



Python – Reinitialize Value lists to K in Dictionary

Sometimes, while working with Python dictionary values, we can have a problem in which we need to reinitialize all the values lists of all keys in dictionary to a constant K. This kind of problem can have application in domains which use data, like Machine Learning and Data Science. Let’s discuss certain way in which this task can be performed.

Input : test_dict = {‘Gfg’ : [[4, 5], [8, 9, 20], [1, 3, 4, ‘oops’]]} 
Output : {‘Gfg’: [[4, 4], [4, 4, 4], [4, 4, 4, 4]]}

Input : test_dict = {‘Gfg’ : “best”} 
Output : {‘Gfg’ : 4} 

Similar Reads

Method 1: Using recursion + type() + dictionary comprehension + items() + loop

The combination of above functionalities can help to solve this problem. In this, we perform the assignment of values using dictionary comprehension and types are tested using type. The items() is used to extract values from dictionary and to perform to each nesting is handled by recursion....

Method #2: Using recursion and isinstance() function

...

Method 3: using a stack data structure and iterative approach.

Approach...

Method 4 : Using the built-in map() function and lambda function

...