So I’m not entirely sure what issue you are experiencing, I’m guessing it’s because calling print(mwodict.values().replace('*',l)) doesn’t actually ‘save state’ per se (Also .values() returns an iterator which doesn’t have a .replace() method so I’m guessing it’s throwing an AttributeError). Nothing… Answer from kylec on forum.freecodecamp.org
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-words-from-dictionary
Python - Replace words from Dictionary - GeeksforGeeks
July 15, 2025 - Using str.replace() in a loop, you can systematically replace specific substrings within a string with new values. This approach is useful for repetitive replacements, such as modifying multiple words or characters.
🌐
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)
Discussions

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
python - String replacement with dictionaries -- follow up - Code Review Stack Exchange
This function takes a dictionary either of the format 'string -> replacement string' or of the format 'regular expression -> replacement string'; in the case of the former, it will replace all instances of 'string' with the provided replacement string, and in the the case of the latter it will replace all expression matches with the provided replacement string. It should be noted that this function, by default, will raise an error if key-value ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 4, 2019
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
python - How can I use a dictionary to do multiple search-and-replace operations? - Stack Overflow
If you want you can iterate through ... for key, value in dictionary.items(). I don't know whether it has advantages in terms of performance, but I think it is more pythonic 2020-11-25T11:29:26.797Z+00:00 ... The downside of the for loop is that it creates replacement ordering problems, e.g. when you have the string Do you like ... More on stackoverflow.com
🌐 stackoverflow.com
April 27, 2017
🌐
Bobby Hadz
bobbyhadz.com › blog › python-replace-words-in-string-using-dictionary
Replace words in a String using a Dictionary in Python | bobbyhadz
Use the str.replace() method to replace words in the string with the dictionary's items. The str.replace() method will return a new string with the matches replaced. ... Copied!my_str = 'site | name' my_dict = { 'site': 'bobbyhadz.com', 'name': ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-string-by-kth-dictionary-value
Python - Replace String by Kth Dictionary value - GeeksforGeeks
April 5, 2023 - Define a function replace_string that takes a string s as input and returns either the value at the k-th index of the dictionary if the string is a key in the dictionary, or the original string if it is not.
🌐
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...
🌐
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
Top answer
1 of 2
6

Ways of optimizing

  • _validate_mappings function
    Two lists keys = [] and values = [] are just used for accumulation and membership check, though inefficiently.
    Instead, the more optimized way is to rely on dict.values() view object converted to set for fast containment check.
    The optimized function would look as (docstrings are skipped for demo):

    def _validate_mappings(mappings: dict) -> None:
        values = set(mappings.values())
        for key, value in mappings.items():
            if key in values:
                raise _KeyValueConflictException(_KEY_VALUE_CONFLICT_EXCEPTION_MSG.format(key, value))
    
  • mapping_replace function in use_regex=True mode and dealing with multiple regex replacements.
    To replace a loop of numerous subsequent regex compilations and substitutions I would suggest a "single-pass" substitution powered by the following features:

    • regex alternation group (...)|(...)|(...) to combine all raw patterns into one
    • Python dict preserves its insertion order since 3.7
    • the respective replacement string is found using Match.lastindex feature (the integer index of the last matched capturing group)

    Although, this trick may require non-overlapping patterns provided in mappings dict.
    The crucial if use_regex: block:

    ...
    if use_regex:
        keys_list = list(mappings.keys())
        replacer = lambda m: mappings[keys_list[m.lastindex - 1]]
        pat = fr"{'|'.join(f'({k})' for k in mappings.keys())}"   # composing regex alternation group
        replaced_string = re.sub(pat, replacer, replaced_string)
    

I've added some extended test case (3rd one) to show how's the regex trick goes:

print(mapping_replace("simple test", {"simple": "complex", "test": "haha"}))
print(mapping_replace("124233 test", {r"\d+": "letters"}, True))
print(mapping_replace("011 test ABCbb11www", {"\d+": "symbols", "[A-Z]+": "@", "w+": "W3W"}, True))
print(mapping_replace("Hello world", {"H": "J", "J": "Y"}, False, validate_mappings=False))  # No exception!
print(mapping_replace("Hello world", {"H": "J", "J": "Y"}))

The output:

complex haha
letters test
symbols test @bbsymbolsW3W
Yello world
raise _KeyValueConflictException(_KEY_VALUE_CONFLICT_EXCEPTION_MSG.format(key, value))
__main__._KeyValueConflictException: The key of 'J' -> 'Y' conflicts with a separate mapping containing the value 'J'.
2 of 2
4

Naming

In many places, functions are described as operating on "mappings" or "set of mappings". As far as I can tell, the dictionary passed as a parameter is a mapping. Thus, the plural form can be removed in various places.

(As a disclaimer, English is not my native language - let me know if I am wrong.)


Unused value

In _validate_mapping, the list keys is populated but never used.


Limitation of the validation

The validation logic seems to be here to ensure that a substitution will not bring a pattern that will be replaced (or would have been replaced) by a different substitution.

This somehow ensure that the order of the dictionary is not important.

An example would be:

print("Yello world" == mapping_replace("Hello world", { "H": "J", "J": "Y"}, False, validate_mapping=False)) # No exception!
print("Jello world" == mapping_replace("Hello world", { "J": "H", "H": "J"}, False, validate_mapping=False)) # No exception!

However, there are various things that may be misleading with the corresponding logic under the assumption that my understanding is valid .

Handling of regexp

Regexp are not properly handled. For instance, this call:

print("\d+ test" == mapping_replace("124233 test", { r"\d+": r"\d+" }, True, validate_mapping=False))

should have the same behaviour with validate_mapping set to True or False. At the moment, it either works or throws the exception.

Opposite situation

There are situations (like above) where the exception is thrown but but probably shouldn't but there are also situations where no exception is thrown but one would be expected. This may give a feeling of "safety" which is not really valid.

An example would be:

print("YYello world" == mapping_replace("Hello world", { "H": "JJ", "J": "Y" }))
print("JJello world" == mapping_replace("Hello world", { "J": "Y", "H": "JJ" }))

Should this throw ?

My expectations

Here is the behavior I'd have expected at least for the regexp case: check that no value from the dict would be matched by any of the keys (using re.search). In reality I do not see any correct way to check for any mapping that could lead to conflicts.

Find elsewhere
🌐
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: ['…
🌐
GeeksforGeeks
geeksforgeeks.org › python › replacing-characters-in-a-string-using-dictionary-in-python
Replacing Characters in a String Using Dictionary in Python - GeeksforGeeks
July 23, 2025 - Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "HellO wOrld".
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.

🌐
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 ...
🌐
Reddit
reddit.com › r/learnpython › q: how can i use a dictionary to replace characters in a string?
Q: How can I use a dictionary to replace characters in a string? : r/learnpython
October 7, 2016 - In the cases where you want to handle this by substituting some "default" value, you can instead use dictionary.get(letter, default). ... I also think this is probably possible to do without dictionaries, but I thought it would be fitting to use a dictionary when making a translator. How do you actually turn Python skills into freelance income?
🌐
Tutorjoes
tutorjoes.in › Python_example_programs › replace_word_dict_in_python
Write a Python program to Replace words from Dictionary
val = "Tutor joe's Computer Education" print("Original string : ",val) dic = {"Computer" : "Software ", "Education" : "Solution"} word = val.split() res = [] for w in word: res.append(dic.get(w, w)) res = ' '.join(res) print("Replaced Strings : " ,res)
🌐
Stack Overflow
stackoverflow.com › questions › 25027485 › replace-values-in-python-dictionary-using-string-variables
replace values in python dictionary using string variables - Stack Overflow
I create python dictionaries for each record that I read.Each record will have mutiple fields..I need to replace the values in the dict using string variables. I have given the example code below. ...
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.19.2 › generated › pandas.Series.replace.html
pandas.Series.replace — pandas 0.19.2 documentation
Replace values given in ‘to_replace’ with ‘value’. ... Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same. Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching ...