Home > Net >  list.append() automatically updates dictionary values?
list.append() automatically updates dictionary values?

Time:09-15

Does anyone know why my dictionary updated automatically even though I didn't use the dict.update() method?

fruits = { "green" : ["kiwi"] }

name = "avocado"    
list_tmp = fruits.get("green")
list_tmp.append(name)

print(fruits)

# output:
 {'green': ['kiwi', 'avocado']}

CodePudding user response:

In Python, both dict and list are mutable. This means that whenever you alter list_tmp, you change fruits.

fruits.get("green") returns not a copy of the list, but the list itself. Then you change the list. The item of the dictionary “points” to an altered list now.

CodePudding user response:

In order to make changes on a copy of your dictionary follow the code below:

import copy


fruits = { "green" : ["kiwi"] }
fruits2=copy.deepcopy(fruits)
name = "avocado"    
list_tmp = fruits2["green"]
list_tmp.append(name)
  • Related