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

Python 3中d.items()与d.keys()疑问:视图对象及代码输出异常

关于Python 3字典视图对象(items()/keys())的疑问解答

Hey there! Let's clear up your confusion around d.items() and d.keys() in Python 3, plus figure out why your code is giving 20 instead of 27.

1. Can view objects (dict_items/dict_keys) be modified?

First off, you're right that d.items() and d.keys() return view objects (specifically dict_items and dict_keys types). These objects have two key traits:

  • They can't be directly modified — you won't find methods like append(), remove(), or pop() on them. Trying to call these will throw an AttributeError.
  • They're dynamic — they're tied directly to the original dictionary. If you add, remove, or modify entries in the dictionary later, the view object will automatically update to reflect those changes.

Here's a quick example to show the dynamic behavior:

my_dict = {'apple': 1, 'banana': 2}
keys_view = my_dict.keys()
print(keys_view)  # Output: dict_keys(['apple', 'banana'])

# Modify the original dictionary
my_dict['cherry'] = 3
print(keys_view)  # Now outputs: dict_keys(['apple', 'banana', 'cherry'])

If you need to modify the collection of keys/items (or keep a static snapshot of their state at a specific time), convert the view to a list first:

static_keys = list(my_dict.keys())
static_keys.append('date')  # This works!
print(static_keys)  # Output: ['apple', 'banana', 'cherry', 'date']
# The original dictionary isn't affected by changes to this list

2. Why am I getting 20 instead of 27?

The most likely culprit here is not accounting for the dynamic nature of view objects. Let's walk through a common scenario that leads to this kind of unexpected output:

Suppose your code looks something like this:

my_dict = {'a': 9, 'b': 9, 'c': 9}
items_view = my_dict.items()  # Get the view object

# Modify the original dictionary later
my_dict['c'] = 2

# Calculate total based on the view
total = sum(value for key, value in items_view)
print(total)  # Output: 9 + 9 + 2 = 20

You probably expected items_view to hold the original values (9,9,9) summing to 27, but since the view is dynamic, it updates when my_dict['c'] changes. So when you calculate the sum, you're using the updated value of 2 instead of 9.

Fix this:

If you need to preserve the state of the dictionary's items/keys at a specific moment, convert the view to a list or tuple before modifying the dictionary:

my_dict = {'a': 9, 'b': 9, 'c': 9}
static_items = list(my_dict.items())  # Create a static list

my_dict['c'] = 2  # Modify the original dict now

total = sum(value for key, value in static_items)
print(total)  # Output: 9 + 9 + 9 = 27 (matches your expectation!)

Another possible scenario is accidentally modifying the dictionary while iterating over the view (which can cause skipped elements or errors), but the dynamic snapshot issue is the most common reason for this kind of sum mismatch.

内容的提问来源于stack exchange,提问作者Zhe Tian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:04:16