Joana Rosado Coelho
Joana Rosado Coelho

Reputation: 11

Find and replace part of dictionary values in python

I have a python dictionary and I would like to find and replace part of the characters in the values of the dictionary. I'm using python 2.7. My dictionary is

data1 = {'customer_order': {'id': '20'},
         'patient': 
             {'birthdate': None,
             'medical_proc': None,
             'medical_ref': 'HG_CTRL12',
             'name': 'Patient_96',
             'sex': None},
          'physician_name': 'John Doe'
         }

I would like to change the underscore to backslash underscore only in the values of the dictionary, in this case only for Patient_96 and HG_CTRL12.

I would like to change it to the following:

 data1 = {'customer_order': {'id': '20'},
          'patient': 
              {'birthdate': None,
               'medical_proc': None,
               'medical_ref': 'HG\_CTRL12',
               'name': 'Patient\_96',
               'sex': None},
          'physician_name': 'John Doe'
         }

Thank you for your help

Upvotes: 1

Views: 1504

Answers (2)

g4ur4v
g4ur4v

Reputation: 3288

>>> for i in data1:
...     if type(data1[i]) is str:
...             if data1[i]:
...                     data1[i] = data1[i].replace('_','\_')
...     elif type(data1[i]) is dict:
...             for j in data1[i]:
...                     if data1[i][j]:
...                             data1[i][j] = data1[i][j].replace('_','\_')
... 
>>> 
>>> 
>>> data1
{'physician_name': 'John Doe', 'customer_order': {'id': '20'}, 'patient': {'medical_ref': 'HG\\_CTRL12', 'medical_proc': None, 'name': 'Patient\\_96', 'birthdate': None, 'sex': None}}

Upvotes: 0

shaktimaan
shaktimaan

Reputation: 12092

This function recursively replaces the underscore in the values of the dictionary with replace_char:

def replace_underscores(a_dict, replace_char):
    for k, v in a_dict.items():
        if not isinstance(v, dict):
            if v and '_' in v:
                a_dict[k] = v.replace('_', replace_char)
        else:
            replace_underscores(v, replace_char)

More on isinstance() here.

Upvotes: 2

Related Questions