You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何通过字典键可修改值,直接操作值却无法保存?

Why doesn't modifying val from dic.values() update the dictionary?

Hey there! This is a super common gotcha with Python's handling of immutable types, so let's break down exactly what's going on.

Your initial approach (that didn't work)

Let's look at the code you first tried:

def add_ten(dic):
    for val in dic.values():
        val += 10
    return dic

When you loop over dic.values(), each val is a temporary variable that references the value from the dictionary. But here's the catch: integers are immutable in Python. That means you can't modify the original integer object itself—when you do val += 10, you're actually creating a brand new integer object (with the value original_val +10) and making val point to this new object.

The problem? The dictionary still holds a reference to the original, unmodified integer. Your val variable is just a separate pointer, so changing it doesn't affect what's stored in the dictionary at all.

Your corrected approach (that works)

Now let's look at the code that did work:

def add_ten(dic):
    for key, val in dic.items():
        dic[key] += 10
    return dic

Here, instead of just working with a temporary val variable, you're using the key to directly access and modify the entry in the dictionary. The line dic[key] +=10 is equivalent to dic[key] = dic[key] +10—you're calculating the new value and then assigning it directly to the key in the dictionary. This updates the dictionary's internal reference to point to the new integer, which is why the changes show up when you return the dictionary.

A quick side note about mutable types

Just to clarify things further: if your dictionary held mutable types (like lists), looping over values() and modifying the variable would affect the dictionary. For example:

my_dict = {1: [5]}
for val in my_dict.values():
    val.append(10)
print(my_dict)  # Output: {1: [5, 10]}

This works because lists are mutable—when you call val.append(10), you're modifying the original list object that the dictionary references, not creating a new one. But since integers are immutable, this trick doesn't work for them.

内容的提问来源于stack exchange,提问作者Samuel Patterson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:22:52