Python mutate existing dict analogous to slice assignment for lists?

Viewed 70

This seemed like a really simple question, but google searches didn't show me much because I am not sure of the right terminology to use here.

Consider the following snippet for list

l1 = [5]

def change_global():
    l1[:] = [1, 2, 3, 4]

if __name__ == '__main__':
    change_global()
    print(l1) # [1, 2, 3, 4]

I have successfully managed to assign to and mutate a global list using the slice notation.

I want something similar for a dictionary. update doesn't work because I want to discard any existing items in the global dictionary. I know I can do:

global_dict.clear()
global_dict.update(new_dict)

But is there a one liner analogous to the list example ?

EDIT:

After looking at a comment I tried the following

d1 = {}

def change_global():
    d1 = {'a': 1, 'b': 2}

This does not change d1 unless I use the global keyword, and yet the slice notation works for the list example. So it definitely means that the slice notation is somehow special here.

0 Answers
Related