Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Reinitialize Value lists to K in 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} 

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.

Python3




# Python3 code to demonstrate working of
# Reinitialize Value lists to K in Dictionary
# Using recursion + type() + dictionary comprehension + items() + loop
 
# helper function
def helper_fnc(ele, K):
    if type(ele) is list:
        return [helper_fnc(val, K) for val in ele]
    elif type(ele) is dict:
        return {key : helper_fnc(val, K) for key, val in ele.items()}
    return K
 
# 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
# Using recursion + type() + dictionary comprehension + items() + loop
res = helper_fnc(test_dict, K)
     
# printing result
print("The Reinitialized dictionary : " + str(dict(res)))


Output : 
The original dictionary : {‘best’: [[4, 5], [8, 9, 20]], ‘is’: 8, ‘gfg’: [4, 6, 7]} 
The Reinitialized dictionary : {‘best’: [[4, 4], [4, 4, 4]], ‘is’: 4, ‘gfg’: [4, 4, 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 recursion and isinstance() function

Approach

Recursion to traverse through the dictionary and modify the values. The idea is to define a recursive function that takes a dictionary as an argument and recursively calls itself for each element in a list value.

Algorithm

1. Define a recursive function to traverse through each key-value pair in the dictionary.
2. If the value is a list, call the same function for each element of the list.
3. If the value is not a list, replace it with K.
4. Return the modified dictionary.

Python3




def reinitialize_dict(test_dict, K):
    def traverse_dict(d):
        for key in d:
            if isinstance(d[key], list):
                for i in range(len(d[key])):
                    if isinstance(d[key][i], list):
                        traverse_dict({key: d[key][i]})
                    else:
                        d[key][i] = K
            else:
                d[key] = K
    traverse_dict(test_dict)
    return test_dict
 
test_dict = {'gfg' : [4, 6, 7], 'is' : 8, 'best' : [[4, 5], [8, 9, 20]]}
K=4
print(reinitialize_dict(test_dict, K))


Output

{'gfg': [4, 4, 4], 'is': 4, 'best': [[4, 4], [4, 4, 4]]}

Time Complexity: O(nml), where n is the number of keys, m is the maximum length of a list value, and l is the maximum length of a sublist.
Auxiliary Space: O(nml), as we are creating a new dictionary for each sublist.

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

We can push the original dictionary on the stack, then we will iterate over each element of the dictionary using a loop, if the element is a dictionary, we push it to the stack, if it is a list, we replace it with the value of K. We will repeat this process until the stack is empty.

Here’s the step-by-step approach:

  • Initialize a stack with the original dictionary.
  • Initialize K value to 4.
  • While the stack is not empty:
    a. Pop the top element from the stack.
    b. If an element is a dictionary, loop over its items and push each value to the stack.
    c. If the element is a list, replace it with the value of K.
  • Return the modified dictionary.

Below is the implementation of the above approach:

Python3




# helper function
def reinitialize_dict(d, K):
    stack = [d]
    while stack:
        ele = stack.pop()
        if isinstance(ele, dict):
            for key, val in ele.items():
                stack.append(val)
        elif isinstance(ele, list):
            for i in range(len(ele)):
                ele[i] = K
    return d
 
# 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': 8, 'best': [4, 4]}

Time complexity: O(N), where N is the total number of elements in the dictionary and its nested structures.
Auxiliary space: O(N), where N is the total number of elements in the dictionary and its nested structures.

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments