I'm trying to take a dictionary and find all of the keys that match key
and replace their value with replace_value
. The dictionaries can in theory be infinitely deep, so it must be done recursively.
My current solution replaces values correctly, but raises an exception saying "maximum recursion depth exceeded while calling a Python object" (not to mention the fact that it's poor use of recursion with no return values).
def replace_item(obj, key, replace_value):
"""
Replaces the dictionary value of key with replace_value in the obj dictionary.
"""
if key in obj:
obj[key] = replace_value
for k, v in obj.items():
if isinstance(v, dict):
item = replace_item(v, key, replace_value)
if item is not None:
item = replace_value
return obj
An example of an operation it would perform would be the following:
Original Dictionary
person_dict = {
"name": "Alex",
"sex": "M",
"title": "Engineer",
"misc": {
"mailbox": "3A",
"work_type": "remote"
}
}
Then I'd make a call to replace_item(person_dict, "work_type", "office")
, which I'd preferably like to change over to returning the updated dictionary (person_dict = replace_item(person_dict, "work_type", "office")
).
Replaced Value Dictionary
person_dict = {
"name": "Alex",
"sex": "M",
"title": "Engineer"
"misc": {
"mailbox": "3A",
"work_type": "office"
}
}
How can I go about fixing my recursion?