Q:

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

belongs to collection: Python Dictionary Programs

0

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]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to swap the position of dictionary ... >>
<< Python program to print sum of key-value pairs in ...