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

Python3中'dict'无'itervalues'属性错误原因及替代方案

Fixing AttributeError: 'dict' object has no attribute 'itervalues' in Python 3

Hey there! Let's break down this error and get your code working properly.

Why does this error happen?

Back in Python 2, dictionaries had separate methods for returning lists vs. iterators: keys(), values(), items() returned full lists, while iterkeys(), itervalues(), iteritems() returned memory-efficient iterators.

Python 3 simplified this entirely: the regular keys(), values(), and items() methods now return iterators by default. The old iter* methods were removed because they were no longer necessary. That's exactly why you're hitting this AttributeError—Python 3 doesn't recognize itervalues() at all.

What to use instead of itervalues()?

Just use values()! In Python 3, dict.values() gives you the same iterator behavior that itervalues() provided in Python 2. No extra hoops to jump through—just swap the method name.

For consistency, here's the full mapping of old Python 2 methods to their Python 3 equivalents:

  • Replace iterkeys() with keys()
  • Replace itervalues() with values()
  • Replace iteritems() with items()

Fixing your code

Your code has two tiny issues to address:

  1. You missed parentheses after itervalues (it should be itervalues()), but even that wouldn't work in Python 3.
  2. The itervalues() method doesn't exist in Python 3—we need to swap it for values().

Here's the corrected, working version:

d1 = {'a':1,'b':2}
d2 = {'c':4,'d':5}
def switch(d1,d2):
    dout = {}
    for d1key,d2val in zip(d1, d2.values()):  # Swapped itervalues for values()
        dout[d1key] = d2val
    return dout
print(switch(d1,d2))  # Output: {'a': 4, 'b': 5}

A quick heads-up: zip(d1, d2.values()) pairs the keys of d1 with the values of d2. This works smoothly as long as both dictionaries have the same number of elements—if they don't, zip will stop at the shorter one.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:37:28