Replace key and value in dictionary python

In this article, we will discuss how to replace multiple words in a string based on a dictionary.

Table of Contents

  • Using str.replace() function
  • Using Regex

Suppose we have a string,

"This is the last rain of Season and Jack is here."

We want to replace multiple words in this string using a dictionary i.e.

{'is' : 'AA',
 'the': 'BBB',
 'and': 'CCC'}

Keys in the dictionary are the substrings that need to be replaced, and the corresponding values in the dictionary are the replacement strings. Like, in this case,

Advertisements

  • “is” should be replaced by “AA”
  • “the” should be replaced by “BBB”
  • “and” should be replaced by “CCC”

The final string should be like,

ThAA AA BBB last rain of Season CCC Jack AA here.

There are different ways to do this. Let’s discuss them one by one.

Using str.replace() function

The string class has a member function replace(to_be_replaced, replacement) and it replaces all the occurrences of substring “to_be_replaced” with “replacement” string.

To replace all the multiple words in a string based on a dictionary. We can iterate over all the key-value pairs in a dictionary and, for each pair, replace all the occurrences of “key” substring with “value” substring in the original string.

For example:

strValue = "This is the last rain of Season and Jack is here."

# Dictionary containing mapping of 
# values to be replaced and replacement values
dictOfStrings = {'is' : 'AA',
                 'the': 'BBB',
                 'and': 'CCC'}

# Iterate over all key-value pairs in dict and 
# replace each key by the value in the string
for word, replacement in dictOfStrings.items():
    strValue = strValue.replace(word, replacement)

print(strValue)

Output:

ThAA AA BBB last rain of Season CCC Jack AA here.

It replaced all the dictionary keys/words in a string with the corresponding values from the dictionary.

Using Regex

In Python, the regex module provides a function sub(pattern, replacement_str, original_str) to replace the contents of a string based on a matching regex pattern.

This function returns a modified copy of given string “original_str” after replacing all the substrings that matches the given regex “pattern” with a substring “replacement_str”.

To replace all the multiple substrings in a string based on a dictionary. We can loop over all the key-value pairs in a dictionary and for each key-value pair, replace all the occurrences of “key” substring with “value” substring in the original string using the regex.sub() function.

For example:

import re

strValue = "This is the last rain of Season and Jack is here."

# Dictionary containing mapping of 
# values to be replaced and replacement values
dictOfStrings = {'is' : 'AA',
                 'the': 'BBB',
                 'and': 'CCC'}

# Iterate over all key-value pairs in dict and 
# replace each key by the value in the string
for word, replacement in dictOfStrings.items():
    strValue = re.sub(word, replacement, strValue)


print(strValue)

Output:

ThAA AA BBB last rain of Season CCC Jack AA here.

It replaced all the dictionary keys/words in a string with the corresponding values from the dictionary.

Summary:

We learned to replace multiple words in a string based on a dictionary in Python.

Home » Python » Python programs

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 »



Can I swap keys and values in dictionary Python?

You can swap keys and values in a dictionary with dictionary comprehensions and the items() method.

How do you replace a key

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

Can you replace a value in a dictionary Python?

When working with dictionaries in Python, to replace a value in a dictionary, you can reassign a value to any key by accessing the item by key. In Python, dictionaries are a collection of key/value pairs separated by commas.

How do you exchange keys and values in a dictionary?

Swap keys and values in a Python dictionary.
dict = {'a': 1, 'b': 2, 'c': 3} ... .
print(dict['b']) ... .
dict = {value:key for key, value in dict.items()} ... .
dict = {'a': 1, 'b': 2, 'c': 3} print(dict) dict = {value:key for key, value in dict.items()} print(dict) ... .
{'a': 1, 'c': 3, 'b': 2} {1: 'a', 2: 'b', 3: 'c'}.