'python replace multiple double characters using a dictionary

I am looking to replace character pairs in a string using a dictionary in python.

It works for single characters but not doubles.

txt = "1122"

def processString6(txt):
  dictionary = {'11': 'a', '22':'b'}
  transTable = txt.maketrans(dictionary)
  txt = txt.translate(transTable)
  print(txt)
 
processString6(txt)

Error Message:

ValueError: string keys in translate table must be of length 1

Desired output:

ab

I'v also tried

s = ' 11  22 ' 
d = {' 11 ':'a', ' 22 ':'b'}
print( ''.join(d[c] if c in d else c for c in s))

but likewise it doesn't work

looking to use a dictionary as opposed to .replace() as I just want to scan the string once as .replace() does a scan for each key,value



Solution 1:[1]

You can use this piece of code to replace any length of strings:

import re

txt = "1122"
 
def processString6(txt):
    dictionary = {'11': 'a', '22':'b'}
    pattern = re.compile(
        '|'.join(sorted(dictionary.keys(), key=len, reverse=True)))
    result = pattern.sub(lambda x: dictionary[x.group()], txt)

    return result

print(processString6(txt))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 matszwecja