×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python program to replace dictionary value for the given keys in another dictionary

Here, we are going to learn how to replace dictionary value for the given keys in another dictionary in Python?
Submitted by Shivang Yadav, on March 25, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

In a dictionary, the keys need to be unique but the values mapped can have duplicate values.

And using the keys, we can find and replace values mapped to it.

We have two dictionaries, one with values and another consisting of the key-value pairs. We need to print the dictionary after replacing values for keys present in replace dictionary.

Example:

Dictionary:
['scala':8, 'Javascript': 7, 'Python':1, 'C++':5, 'Java':3]

ReplaceDictionary:
['Javascript': 2, 'C++': 9]

UpdatedDictionary:
['scala':8, 'Javascript': 2, 'Python':1, 'C++':9, 'Java':3]

We will loop through the dictionary and check if the matching key is present in the updateDict.

If yes, replace the mapped value otherwise, continue the loop.

After the loop gets over print the dictionary.

Program to replace dictionary value for the given keys in another dictionary

# Python program to replace dictionary value 
# for the given keys in another dictionary

# Initialising dictionary
myDict = {'Scala': 2, 'Javascript': 1, 'Python': 8, 'C++': 1, 'Java': 4}
updateDict = {"Scala"  : 10, "Python" : 17}

print("Dictionary = ", end = " ")
print(myDict)

# Updating dictionary using update values
for sub in myDict:
    if sub in updateDict:
        myDict[sub]  = updateDict[sub]
  
# Printing the dictionary
print("Updated dictionary = ", end = " ")
print(myDict)

Output:

Dictionary =  {'C++': 1, 'Javascript': 1, 'Python': 8, 'Scala': 2, 'Java': 4}
Updated dictionary =  {'C++': 1, 'Javascript': 1, 'Python': 17, 'Scala': 10, 'Java': 4}

Python Dictionary Programs »



Related Programs

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.