Easiest way to replace a string using a dictionary of replacements?


Question

Consider..

dict = {
'Спорт':'Досуг',
'russianA':'englishA'
}

s = 'Спорт russianA'

I'd like to replace all dict keys with their respective dict values in s.

1
69
3/8/2010 1:19:41 PM

Accepted Answer

Using re:

import re

s = 'Спорт not russianA'
d = {
'Спорт':'Досуг',
'russianA':'englishA'
}

pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b')
result = pattern.sub(lambda x: d[x.group()], s)
# Output: 'Досуг not englishA'

This will match whole words only. If you don't need that, use the pattern:

pattern = re.compile('|'.join(d.keys()))

Note that in this case you should sort the words descending by length if some of your dictionary entries are substrings of others.

89
3/8/2010 1:48:51 PM

You could use the reduce function:

reduce(lambda x, y: x.replace(y, dict[y]), dict, s)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon