简体   繁体   English

RuntimeError:OrderedDict在迭代过程中发生了变异

[英]RuntimeError: OrderedDict mutated during iteration

I'm relatively new to python3 & am trying to iterate over a preexisting OrderedDict() to remove entries with None as the value. 我对python3来说相对较新,并且正在尝试遍历预先存在的OrderedDict()来删除值为None条目。 In python2 this wasn't a problem, but it's my understanding that the removal of dict.iteritems() (etc...) was due to some changes in the way dict.items() is returned. 在python2中,这不是问题,但据我了解,移除dict.iteritems() (等)是由于返回dict.items()的方式发生了一些变化。

I reeeeeeeeeeally want to avoid copying the dictionary... 再也不想避免复制字典了。

I'm going to be doing (potentially hundreds of) thousands of these & I don't want to double the amount of memory I'm using just to remove null entries from an OrderedDict . 我将要做(可能成百上千)这样的事情,而且我不想将仅用于从OrderedDict删除空条目的内存量加倍。

Here's the code that's throwing the error: 这是引发错误的代码:

class DefaultHeaders(OrderedDict):
    def __init__(self, loop=None):
        super(DefaultHeaders, self).__init__()

        self['User-Agent'] = "Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1" # <--(dummy User-Agent header for consistent response-format)
        self['X-Search-ClientIP'] = gethostbyname(gethostname())                                                 
        self['X-MSEdge-ClientID'] = None
        self['Accept'] = None
        self['Accept-Language'] = None
        self['X-Search-Location'] = None

        self._clean1() # <--raises error
        # self._clean2() # <--raises error
        # self._clean3() # <--raises error

    def _clean1(self):
        for k, v in self.items():
            if k in ('count', 'offset'):
                pass
            elif not v: del self[k]

    def _clean2(self):
        for k, v in list(self.items()):
            if k in ('count', 'offset'):
                pass
            elif not v: del self[k]


    def _clean3(self):
        _iter_this = list(self.items())
        for k, v in _iter_this:
            if k in ('count', 'offset'):
                pass
            elif not v: del self[k]

And here's the error I'm getting: 这是我得到的错误:

...
    for k, v in self.items():
RuntimeError: OrderedDict mutated during iteration

Process finished with exit code 1

(>_<) i feel a little dumb but that's not new lol. (> _ <)我感到有点傻,但这不是新的笑。 Thanks to everyone who posted answers. 感谢所有发布答案的人。 Here's what I've got now: 这是我现在得到的:

def _clean(self):
    for k in list(self.keys()):
        if k in ('count', 'offset'):
            pass
        elif not self[k]:
            del self[k]

Also I realized copying isn't an option. 我也意识到复制不是一个选择。 I'd need to reassign self & creating a new instance of my class calls _clean() producing infinite recursion. 我需要重新分配self并创建类的新实例,调用_clean()产生无限递归。

What about iterating the dictionary with an index?: 如何用索引迭代字典?

    def _clean4(self):
        i = 0

        while i < len(self):
            if self.keys()[i] not in ('count', 'offset') and not self[self.keys()[i]]:
                del self[self.keys()[i]]
            else:
                i = i + 1

您是否尝试过:

[ordered_dict.pop(k) for k in ordered_dict if k not in ['count', 'offset'] or ordered_dict[k] == None]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RuntimeError:OrderedDict在迭代期间发生变异(Python3) - RuntimeError: OrderedDict mutated during iteration (Python3) Django Rest框架和python3.5 OrderedDict在迭代过程中发生了变异 - Django rest framework and python3.5 OrderedDict mutated during iteration 如何修复 RuntimeError:在 Python 迭代期间 deque 发生变异 - How to fix RuntimeError: deque mutated during iteration in Python RuntimeError:迭代期间字典改变了大小 - 在defaultdict上使用iteritems进行迭代 - RuntimeError: dictionary changed size during iteration - During Iteration with iteritems on a defaultdict RuntimeError:词典在迭代过程中更改了大小 - RuntimeError: dictionary changed size during iteration RuntimeError:字典在迭代期间使用 defaultdict() 改变了大小 - RuntimeError : dictionary changed size during iteration with defaultdict() Python,RuntimeError:字典在迭代过程中更改了大小 - Python, RuntimeError: dictionary changed size during iteration RuntimeError:字典在python迭代期间更改了大小 - RuntimeError: dictionary changed size during iteration in python PySpark RuntimeError:设置迭代过程中更改的大小 - PySpark RuntimeError: Set changed size during iteration python RuntimeError:字典在迭代期间改变了大小 - python RuntimeError: dictionary changed size during iteration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM