via dict.update() function

In case you need a declarative solution, you can use dict.update() to change values in a dict.

Either like this:

my_dict.update({'key1': 'value1', 'key2': 'value2'})

or like this:

my_dict.update(key1='value1', key2='value2')

via dictionary unpacking

Since Python 3.5 you can also use dictionary unpacking for this:

my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

via merge operator or update operator

Since Python 3.9 you can also use the merge operator on dictionaries:

my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

Or you can use the update operator:

my_dict |= {'key1': 'value1', 'key2': 'value2'}
Answer from Rotareti on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-words-from-dictionary
Python - Replace words from Dictionary - GeeksforGeeks
July 15, 2025 - The code constructs a regex pattern dynamically to match whole words from the dictionary keys using re.sub(). A lambda function is used to replace each matched word with its corresponding value from the dictionary
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-dictionary-value-from-other-dictionary
Python - Replace dictionary value from other dictionary - GeeksforGeeks
April 10, 2023 - In this, we run a loop for each key in target dictionary and update in case the value is present in other dictionary. ... # 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))
Discussions

How do I replace a string using a dictionary?
Instead of iterating over the dictionary, iterate over your input string: out_string = "" for letter in string_encode: out_string += dict_cipher.get(letter, " ") print(out_string) (dictionary.get(key, default) will return the value associated with key if key is present, and default if it isn't; this will let you handle non-alpha characters in your input.) More on reddit.com
🌐 r/learnpython
3
10
October 31, 2021
python - How can I use a dictionary to do multiple search-and-replace operations? - Stack Overflow
I have to replace text like "north", "south", etc. with "N", "S" etc. in address fields. I thought of making a dictionary to hold the replacements. Suppose w... More on stackoverflow.com
🌐 stackoverflow.com
Help with replace()
Note to the original code: You want to create a different number of strings. This cannot be done by using str.replace() because this function changes a string to a different string. This function cannot split or join strings which would be needed to change their number · This is sort of a ... More on discuss.python.org
🌐 discuss.python.org
19
0
July 20, 2022
Replacing a specific value in a dictionary
Hi, Below a part of the program I am writing, I have difficulty to make the last part function correctly. mwodict is a dictionary where the keys are the letters of a word chosen randomly with choice method, and the values are * The user should type a letter to try guessing the hidden word. ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
2
0
February 26, 2019
🌐
Reddit
reddit.com › r/learnpython › how do i replace a string using a dictionary?
r/learnpython on Reddit: How do I replace a string using a dictionary?
October 31, 2021 -

I want the replace a word given by the input to create a cipher, but I can’t figure out how to change each value at the same time to produce a new string.

For example the dictionary is {a: b, b: c, c: 2….} Then I want the inputted string to change each letter in the string/word to what it corresponds to in the dictionary so that a new string is generated with no letters remaining the same.

Right now this is my code:

cipher = input('Please enter the cipher text:')

import string

letters = string.ascii_lowercase

letters_list = list(letters)

cipher_list = list(cipher)

pair_letters_cipher = zip(letters_list, cipher_list)

dict_cipher = dict(pair_letters_cipher)

string_encode = input('Please enter text to encode:')

for letters, cipher in dict_cipher.items():

string_encode = string_encode.replace(letters.lower(), cipher)

print(string_encode)
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-37.php
Python: Replace dictionary values with their average - w3resource
Write a Python program to update a dictionary so that each key's value becomes the sum of its original value and another corresponding value from a second dictionary.
🌐
DataCamp
campus.datacamp.com › courses › writing-efficient-code-with-pandas › replacing-values-in-a-dataframe
Replace values using dictionaries | Python
The syntax is very simple: we map each value we want to replace to the value we want to replace it with, using the colon symbol. We could do the same thing with lists, but it's a more verbose. If we compare both methods, we can see that dictionaries run approximately 55% faster.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › How-to-replace-values-of-a-Python-dictionary
How to replace values of a Python dictionary?
You can assign a dictionary value to a variable in Python using the access operator []. For example, Example my_dict = { 'foo': 42, 'bar': 12.5 } ne
🌐
IncludeHelp
includehelp.com › python › replace-dictionary-value-for-the-given-keys-in-another-dictionary.aspx
Python program to replace dictionary value for the given keys in another dictionary
We need to print the dictionary after replacing values for keys present in replace dictionary. ... 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]
🌐
EyeHunts
tutorial.eyehunts.com › home › python replace dictionary key | example code
Python replace dictionary key | Example code
January 20, 2023 - A simple example changes the key of an entry in a Python dictionary. ... dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15} # changing 'A' key dic1['Z'] = dic1['A'] del dic1['A'] print(dic1) ... It will take one step only. dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15} # changing 'A' key dic1['Z'] = dic1.pop('A') print(dic1) Output: {‘B’: 5, ‘C’: 10, ‘D’: 15, ‘Z’: 1} ... Let’s replace all keys of the dictionary.
🌐
Python.org
discuss.python.org › python help
Help with replace() - Python Help - Discussions on Python.org
July 20, 2022 - lst = [‘company1_hat’, ‘company1_glasses’, ‘company2_hat’] nlst = [el.replace(‘_’, ‘', '’) for el in lst] print(nlst) the output: ['company1", "hat', 'company1", "glasses', 'company2", "hat'] the desired output: ['company1', 'hat', 'company1', 'glasses', 'company2', 'hat']
🌐
W3Schools
w3schools.com › python › python_dictionaries_change.asp
Python - Change Dictionary Items
You can change the value of a specific item by referring to its key name.
🌐
Finxter
blog.finxter.com › home › learn python blog › python dictionary: how to create, add, replace, retrieve, remove
Python Dictionary: How to Create, Add, Replace, Retrieve, Remove - Be on the Right Side of Change
April 4, 2022 - To add a new key:value pair to a dictionary, add a key inside the square brackets at the end of the dictionary reference. Assign this key a value using the equals (=) sign. The code below adds the composer Bach and his birth year and displays the output. ... Use the method to replace a key in an existing key:value pair.
🌐
W3Schools
w3schools.com › python › gloss_python_change_dictionary_item.asp
Python Change Values in a Dictionary
Python Dictionaries Tutorial Dictionary Access Dictionary Items Loop Dictionary Items Check if Dictionary Item Exists Dictionary Length Add Dictionary Item Remove Dictionary Items Copy Dictionary Nested Dictionaries
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Replacing a specific value in a dictionary - Curriculum Help - The freeCodeCamp Forum
February 26, 2019 - Hi, Below a part of the program I am writing, I have difficulty to make the last part function correctly. mwodict is a dictionary where the keys are the letters of a word chosen randomly with choice method, and the values are * The user should type a letter to try guessing the hidden word. l is the input() letter, in case the letter typed is one of the hidden word letters, the program should return the values ‘x’ of the word except the value of l which should be replacing it’s corresponding...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-replace-words-in-string-using-dictionary
Replace words in a String using a Dictionary in Python | bobbyhadz
Use a for loop to iterate over the dictionary's items. Use the str.replace() method to replace words in the string with the dictionary's items.
🌐
Python.org
discuss.python.org › ideas
Feature Proposal: Multi-String Replacement Using a Dictionary in the .replace() Method - Ideas - Discussions on Python.org
October 21, 2024 - Summary: I would like to propose an extension to the .replace() method to allow multiple substring replacements in a string using a dictionary. Currently, .replace() accepts only two arguments (the value to be replaced and the replacement value), which results in the need for multiple calls ...
Top answer
1 of 1
9

Mostly this looks good, but I’ll make a few suggestions:

Boolean arguments in your function signature

These control whether certain strings/mappings are lowercased first. I think this behaviour should be removed from keymap_replace(). It's scope creep: it’s gone from being string replacements to more complicated string manipulations. I’d leave that sort of manipulation to the caller.

(And you could continue to add options like this: what about uppercasing the string, or reversing it, or another pattern. Rather than muddling up your function with this, I’d just take it out.)

That makes the arguments simpler, and simplifies the function definition as well.

But if you really want those parameters in there, then I’d suggest making them keyword-only. In Python 3, you can insert an asterisk as so:

def keymap_replace(
    string: str, 
    mappings: dict,
    *,
    lower_keys=False,
    lower_values=False,
    lower_string=False,
) -> str:

and when the function is called, those boolean arguments have to be as keyword arguments, not positional. There can never be ambiguity in how the function is being used.

Dictionaries are unordered

There’s a possibility for ambiguity, or for substitutions to be chained. For example:

keymap_replace('Hello world', {
    'J': 'K',
    'H': 'J'
})

Should this call return "Jello world" or "Kello world"?

I think the first is more natural – I don’t expect substitutions to be chained – but when I tried the function, I got the latter. You should try to make this less confusing.

One possibility that springs to mind:

replaced_string = ''.join(mappings.get(char, char) for char in string)

Each character in the original string is subject to at most one substitution.