I have a dictionary that looks like:
my_dict = {
'_id': '12powensjdm683ma23',
'data': {
'account': 'FUNDING',
'form': {
'accounts': {
'credit': {
'name': 'JOBEN BETETI BORGES',
'account_number': 'YYYYYYYY',
'address': {
'line3': '0.',
'line2': 'rial, Santo André, SP, BR,09080-50',
'line1': '1600 APTO.51 TORRE 3 Avenida Indust'
}
},
'receiving': {
'name': 'THE BANK OF NEW YORK MELLON',
'aba_number': 'XXXXXXXX',
'address': {
'line1': 'NEW YORK, NY, US',
'line2': '',
'line3': ''
}
}
}
}
}
}
I am trying to create a function that will loop through each key value pair and determine if the value has "offending" values like the é in the municipality Santo André.
line2': 'rial, Santo André, SP, BR, 09080-50',
If it is, then we will normalize the value to a normal e. So it'd look like this:
line2': 'rial, Santo Andre, SP, BR, 09080-50',
In addition to this, I would like this to be dynamic, so that the code doesn't have to explicitly look for my_dict['data']['form']['accounts']['credit'] or my_dict['line2']. It should just loop through each key value pair, and if that value is "offending", then update it (I have other dictionaries that I need to update in a similar way, but their keys, lengths and depths are varying).
I think I really just need a way to loop through every level of a dictionary that has any number of particular levels.
I initially thought to recursively run the function through this dynamic_input() function I have but the input takes string values. However, with the recursive function, the values might also be another dict. dynamic_input() currently takes in a string value.
def dynamic_input(input):
''' Clean the given dynamic input of any offending formats or characters.
Parameters: str(input)
Returns: str(cleaned_input)
'''
# remove excessive spaces
input = " ".join(input.split())
# remove undesired characters
input = re.sub("\\n|\\r|\\t|'|\"", '', input)
# special character conversion
input = unicodedata.normalize('NFD', input)
input = re.sub(r'[^\x00-\x7f]', '', input)
# return
return input