简体   繁体   中英

Why can I change dict values by referencing keys but not the values themselves?

Here, is my code:

# Write your add_ten function here:
def add_ten(dic):
  for key, val in dic.items():
    dic[key] += 10
  return dic
# Uncomment these function calls to test your  function:
print(add_ten({1:5, 2:2, 3:3}))
# should print {1:15, 2:12, 3:13}
#print(add_ten({10:1, 100:2, 1000:3}))
# should print {10:11, 100:12, 1000:13}

This works, however initially I did:

for val in dick.values():
    val += 10

Using visualizer, this added 10 to the value, but the value was not saved. Why?

In this loop:

for val in dick.values():
    val += 10

val is not a reference to a mutable value in the dictionary. val += 10 is implemented as val = val + 10 -- you are reassigning the local variable val rather than modifying the original dictionary value that it was initialized with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM