[SOLVED] Modifying dictionary inside a function

Issue

I have the following code:

def modify_dict(my_dict):
    my_dict = {'b': 2}
    print(my_dict)


def main():
    my_dict = {'a': 1}
    modify_dict(my_dict)
    print(my_dict)

if __name__ == '__main__':
    main()

and it’s output is:

{'b': 2}
{'a': 1}

My question is why are the changes done to the dictionary inside the function aren’t being reflected in the main() function?
Also, how can I update the dictionary inside the function so that the changes are reflected outside of the function?

Solution

The my_dict parameter of modify_dict is a local variable to your function. It contains a reference to your dictionary, but it itself is simply a local variable. If you reach in and modify the dictionary it points to, that would work. For example:

def modify_dict(my_dict):
    my_dict['b'] = 2
    print(my_dict)

Will add to your dictionary. In effect, you are simply assigning a new dictionary to a local variable called my_dict in your function.

As @vmonteco suggests, the best way to achieve this is to simply return the new dictionary from your function and assign the return value.

Answered By – srowland

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published.