Open In App

Python – Replace dictionary value from other dictionary

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

Given two dictionaries, update the values from other dictionary if key is present in other dictionary.

Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 8, “Geeks” : 9}, updict = {“Geeks” : 10, “Best” : 17} 
Output : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 17, ‘for’: 8, ‘Geeks’: 10} 
Explanation : “Geeks” and “Best” values updated to 10 and 17. 

Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 8, “Geeks” : 9}, updict = {“Geek” : 10, “Bet” : 17} 
Output : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 10, ‘for’: 8, ‘Geeks’: 9} 
Explanation : No values matched, hence original dictionary.

Method #1 : Using loop 

This is brute way in which this task can be performed. In this, we run a loop for each key in target dictionary and update in case the value is present in other dictionary.

Python3




# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using loop
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing updict
updict = {"Gfg"  : 10, "Best" : 17}
 
for sub in test_dict:
     
    # checking if key present in other dictionary
    if sub in updict:
        test_dict[sub]  = updict[sub]
 
# printing result
print("The updated dictionary: " + str(test_dict))


Output

The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using dictionary comprehension

This is one liner approach in which this task can be performed. In this, we iterate for all the dictionary values and update in a one-liner manner in dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using dictionary comprehension
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing updict
updict = {"Gfg"  : 10, "Best" : 17}
 
res = {key: updict.get(key, test_dict[key]) for key in test_dict}
 
# printing result
print("The updated dictionary: " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}

Time complexity: O(n), 

Auxiliary space: O(m), 

Method #3: Using dict.update() method

This program updates the values of certain keys in a dictionary by using the update() method. It initializes two dictionaries (test_dict and updict), updates the values of the keys “Gfg” and “Best” in test_dict using the corresponding values in updict, and then prints the updated test_dict.

Python3




# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using dict.update() method
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing updict
updict = {"Gfg"  : 10, "Best" : 17}
 
# updating dictionary using dict.update() method
test_dict.update(updict)
 
# printing result
print("The updated dictionary: " + str(test_dict))


Output

The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}

Time complexity: O(m), where m is the size of the updict.

Auxiliary space: O(1), as the algorithm updates the existing dictionary in place and does not use any additional space proportional to the size of the input.

Method #5: Using the built-in map() function and a lambda function

In this method, we first create a list of updated values by mapping a lambda function to the keys of the original dictionary. The lambda function checks if the key is present in the second dictionary, and if it is, returns the corresponding value from the second dictionary. Otherwise, it returns the value from the original dictionary.

Python3




test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
updated_values = map(
    lambda key: updict[key] if key in updict else test_dict[key], test_dict)
updated_dict = dict(zip(test_dict.keys(), updated_values))
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
 
updated_values = map(
    lambda key: updict[key] if key in updict else test_dict[key], test_dict)
updated_dict = dict(zip(test_dict.keys(), updated_values))
 
print("The updated dictionary: " + str(updated_dict))


Output

The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}

The time complexity of this code is O(N), where N is the number of key-value pairs in the test_dict.
The auxiliary space complexity of this code is also O(N), as we use a map() object to store the updated values, and then we create a new dictionary using the zip() function.

Method 6: Using defaultdict

Use the defaultdict class from the collections module to create a new dictionary with default values set to the values of the original dictionary. We will then update the values of the keys present in the updict.

Step-by-step approach:

  • Create a defaultdict with default values from the original dictionary
  • Update the values of the keys present in the updict
  •  Convert the defaultdict back to a regular dictionary

Below is the implementation of the above approach:

Python3




from collections import defaultdict
 
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
 
# create a defaultdict with default values from the original dictionary
default_dict = defaultdict(lambda: None, test_dict)
 
# update the values of the keys present in the updict
for key, value in updict.items():
    default_dict[key] = value
 
# convert the defaultdict back to a regular dictionary
updated_dict = dict(default_dict)
 
print("The updated dictionary: " + str(updated_dict))


Output

The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}

Time complexity: O(N+M), where N is the number of keys in the original dictionary and M is the number of keys in the updict.
Auxiliary space: O(N), where N is the number of keys in the original dictionary.



Similar Reads

Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Python - Replace String by Kth Dictionary value
Given a list of Strings, replace the value mapped with the Kth value of mapped list. Input : test_list = ["Gfg", "is", "Best"], subs_dict = {"Gfg" : [5, 6, 7], "is" : [7, 4, 2]}, K = 0 Output : [5, 7, "Best"] Explanation : "Gfg" and "is" is replaced by 5, 7 as 0th index in dictionary value list. Input : test_list = ["Gfg", "is", "Best"], subs_dict
6 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Replace sublist with other in list
Sometimes, while working with Python, we can have a problem in which we need to manipulate a list in such a way that we need to replace a sublist with another. This kind of problem is common in the web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop ( When sublist is given ) This method is
10 min read
Python - Replace index elements with elements in Other List
Sometimes, while working with Python data, we can have a problem in which we have two lists and we need to replace positions in one list with the actual elements from other list. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This is one way to solve this problem. In this we just iterate through
6 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Practice Tags :