Skip to content

Instantly share code, notes, and snippets.

@schbrongx
Last active May 9, 2017 12:35
Show Gist options
  • Save schbrongx/2b5de492d06e472de0a20e38f7ad3078 to your computer and use it in GitHub Desktop.
Save schbrongx/2b5de492d06e472de0a20e38f7ad3078 to your computer and use it in GitHub Desktop.
def replace_in_nested_dict(dict_in, str_old, str_new):
''' loop over ALL levels of a dictionary, replacing str_old with str_new
i am working with collections.OrderedDict(), which may be replaced with
an ordinary dict. i have tested it with both.
'''
if not isinstance(dict_in, dict):
raise TypeError('First argument has to be of type dict. Is type: ' + type(dict_in))
if not isinstance(str_old, str):
raise TypeError('Second argument has to be of type str. Is type: ' + type(str_old))
if not isinstance(str_new, str):
raise TypeError('Second argument has to be of type str. Is type: ' + type(str_new))
dict_out = collections.OrderedDict()
for key, value in dict_in.iteritems():
# if the current value is a dict, we have to go through it, too
if isinstance(value, dict):
dict_out[key] = replace_in_nested_dict(value, str_old, str_new)
elif isinstance(value, str) and (str_old in value):
dict_out[key] = value.replace(str_old, str_new)
else:
dict_out[key] = value
return dict_out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment