Other questions
This is a spin-off from How can I replace a key-value pair in a nested dictionary with the value from the same key-value pair? where the answer is working only in a one-time-nested dictionary. And it is a spin-off from Loop through all nested dictionary values? which I could not get to work on this problem.
Before:
I have a dictionary that is nested many times.
dict_nested = {
"key_":{
"key0a":{
"key1a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b"},
"key1b":"value1b"},
"key0b":{
"key_XYZ":{
"key1a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b"},
"key1b":"value1b"}
}
}
}
After:
The result should look like this:
dict_nested_new = {
"key_":{
"key0a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b",
"key1b":"value1b"},
"key0b":{
"key_XYZ":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b",
"key1b":"value1b"}
}
}
}
Modifying a Python dict while iterating over it
When I looped through the items of the dictionary to delete / replace, I got the error
RuntimeError: dictionary changed size during iteration
which needs somehow to be avoided.
How can I replace the "key1a":SOME_VALUE
key-value pair with its value each time it occurs somewhere in the dictionary?