Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遍历字典子类中的值_Python_Python 2.7 - Fatal编程技术网

Python 遍历字典子类中的值

Python 遍历字典子类中的值,python,python-2.7,Python,Python 2.7,我有一个从OrderedDict继承的类。我希望能够遍历它的值,而不是它的键 我相信下面的代码应该可以工作,但它不能。它没有打印值“1”和“2”,而是给出了某种递归错误(如代码下面所示) 我得到的错误如下: File "T:\***\Test024.py", line 8, in __iter__ for value in self.values(): File "C:\Python27\Lib\collections.py", line 111, in values retur

我有一个从OrderedDict继承的类。我希望能够遍历它的值,而不是它的键

我相信下面的代码应该可以工作,但它不能。它没有打印值“1”和“2”,而是给出了某种递归错误(如代码下面所示)

我得到的错误如下:

File "T:\***\Test024.py", line 8, in __iter__
    for value in self.values():
File "C:\Python27\Lib\collections.py", line 111, in values
    return [self[key] for key in self]
RuntimeError: maximum recursion depth exceeded while calling a Python object

为什么上面的例子不起作用?我知道我可以像a.values():中的thing那样使用循环
对值进行迭代,但是我想避免对字典而不是列表使用
.values()
的不一致性。我确实需要在代码的其他部分使用字典的功能。

正如您在异常回溯中看到的,
orderedict.values
在dict上迭代:

from collections import OrderedDict

class A(OrderedDict):
    def __init__(self):
        super(A, self).__init__()    

    def __iter__(self):
        for value in self.values():
            yield value
        return

a = A()
a[1] = "one"
a[2] = "two"

for thing in a:
    print str(thing)
File "/usr/lib64/python2.7/collections.py", line 123, in values
return [self[key] for key in self]
由于您已经重写了
\uuu iter\uu
函数,这将导致无限递归

要克服此问题,您必须覆盖
函数,例如:

def values(self):
    return [self[key] for key in OrderedDict.__iter__(self)]

这是一个非常粗糙的解决方案,但通过修改原始的
OrderedDict
实现(
/usr/local/lib/python2.7/collections.py:90
),您可以执行以下操作:

from collections import OrderedDict

class A(OrderedDict):
    def __init__(self):
        super(A, self).__init__()

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        # Traverse the linked list in order.
        root = self._OrderedDict__root
        curr = root[1]
        while curr is not root:
            yield self[curr[2]]
            curr = curr[1]

a = A()
a[1] = "one"
a[2] = "two"

for thing in a:
    print str(thing)

[错误评论]删除
return
这样做有什么意义?人们期望dict在迭代时返回键,而不是值。只需使用
a.itervalues()
@sangheestyle,这不会有任何作用。@AshwiniChaudhary啊,你说得对。但是原始代码在我的本地计算机上工作。这就是我困惑的原因。抱歉。@p请注意,我的观点是从
\uuuu iter\uuuu
返回值是不一致的行为,除了您之外,没有人会期望dict在其迭代过程中返回值非常清楚,看到它的人会知道发生了什么。有了这句话,你可以做:
在super(A,self)中为k。在你的
中产生self[k]
,以获得值。
$ ./foo.py
one
two