Recursively Replace Dictionary Values With Matching Key
Solution 1:
You have some strange behavior where you are expecting a return
but you don't have one. Also your description implies it should replace nested keys, but your code you will miss when a dictionary at the top level does not have the key but at a lower level does. I believe the below code accomplishes what you described:
defreplace_item(obj, key, replace_value):
for k, v in obj.items():
ifisinstance(v, dict):
obj[k] = replace_item(v, key, replace_value)
if key in obj:
obj[key] = replace_value
return obj
EDIT: As @dashiell suggested, moving the top level reassignment after the recursive search/replace avoids the infinite recursion trap of having key
exist in the replace_value
.
Solution 2:
Here's a functional-style take:
def replace(obj, key, val):
return {k: replace(valif k == key else v, key, val)
for k,v in obj.items()} if isinstance(obj, dict) else obj
It's not efficient in Python (since all values/subdicts are re-created), but demonstrates how to solve your problem without side-effects and without mutating objects.
Solution 3:
defreplace_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():
ifisinstance(v, dict):
replace_item(v, key, replace_value)
I think this is enough.. no need of extra variables, and in most of the systems, default recursion depth is around 1000, you can change it https://docs.python.org/3/library/sys.html#sys.setrecursionlimit
Post a Comment for "Recursively Replace Dictionary Values With Matching Key"