So python dictionaries are mutable objects, hence when modified inside a function, the modification reflects also outside the function. However, when the function parameter is reassigned inside the function, the effect is only local.
For example consider the following code:
import json
def modify_dict1(a: dict) -> None:
new_dict = {1: "one"}
a = new_dict
def modify_dict2(a: dict) -> None:
a[1] = "1"
a_global = {1: "ONE"}
print(json.dumps(a_global, indent=2))
modify_dict1(a_global)
print(json.dumps(a_global, indent=2))
modify_dict2(a_global)
print(json.dumps(a_global, indent=2))
which prints:
{
"1": "ONE"
}
{
"1": "ONE"
}
{
"1": "1"
}
I was expecting the output to be:
{
"1": "ONE"
}
{
"1": "one"
}
{
"1": "1"
}
Why the reassignment to the local variable has no effect outside the function?