Search code examples
pythonpython-re

Replacing a string matching to a key with the value in dictionary using re module


I have a string '09 Mai 2022'. I am trying to replace it by a value in the dictionary

Code

import re

dictionary = {"Januar":"January","Februar":"February","März":"March","April":"April","Mai":"May","Juni":"June",
             "Juli":"July","August":"August","September":"September","Oktober":"October","November":"November",
             "Dezember":"December"}

dict_comb = "|".join(dictionary)
date = '09 Mai.2022'
dates_fo = re.sub(dict_comb, dictionary[k] for k in dict_comb, date)
print(dates_fo)

Expected Output

09 May. 2022

Solution

  • Try this:

    import re
    dictionary = {"Januar":"January","Februar":"February","März":"March","April":"April","Mai":"May","Juni":"June",
                 "Juli":"July","August":"August","September":"September","Oktober":"October","November":"November",
                 "Dezember":"December"}
    
    pattern = '|'.join(dictionary.keys())
    
    date = '09 Mai.2022'
    
    dates_fo = re.sub(pattern, lambda m: dictionary.get(m.group(0)), date, flags=re.IGNORECASE)
    

    Output:

    >>> print(dates_fo)
    09 May.2022