I have a nested dictionary where every element can be of any type including a list or dictionary. I'm looking for a method to update any key at any depth with a particular value. (So the replacement occurs if the target value is not a list or dictionary)
e.g
{
'a': 1,
'b': 2,
'c': [{'a': 2, 'b': 3}],
'd': [{'d_d': {'a': 1, 'b': 2}}],
'e': {'a': 4},
}
would become
{
'a': 'xx',
'b': 2,
'c': [{'a': 'xx', 'b': 3}],
'd': [{'d_d': {'a': 'xx', 'b': 2}}],
'e': {'a': 'xx'},
}
where the function takes a dictionary, key and new value like so
update_nested(dict, key='a', value='xx')
Let's look at which parts you need and how to implement them:
there are three different methods that help you to iterate over a dictionary:
iterating over all keys in the dict. e.g.
for key in {"Hello": 10, "World", 20}.keys():
print(k)
# output: Hello\nWorld
iterating over all (key, value) tuples in the dict. for k, v in d.items()
iterating over all values in the dict. for v in d.values()
When you have nested structures a good concept would recursion
In short: You call the same function in itself with different parameters.
putting both concepts together.
Possible final code:
def update_nested(in_dict, key, value):
for k, v in in_dict.items():
if key == k:
in_dict[k] = value
elif isinstance(v, dict):
update_nested(v, key, value)
elif isinstance(v, list):
for o in v:
if isinstance(o, dict):
update_nested(o, key, value)
You should never use a builtin name/type as a variable name. In your case dict. This will override the builtin type and can lead to unexpected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With