1

I looked through the database of answers pertaining to this topic and couldn't find an answer, essentially I'm looping through a dictionary, I'm getting the, "dictionary changes size," runtime error yet I'm popping out one key and value and inserting another before the iteration resumes.

       for patterns in dict_copy.keys():
            new_tuple = ()
            for items in range(len(patterns)):
                if patters[items] not in exclusion:
                    new_tuple += (patterns[items],)
            dict_copy[new_tuple] = dict_copy.get(patterns)
            dict_copy.pop(patterns)

The dictionaries I'm working with are in the form: {("A","B","C","D"):4, ("B","A","C","D") "2...} I'm pretty much just confused over the fact that it thinks I'm chaning the dictionary size

4

2 回答 2

1

The error is slightly misleading. What it's trying to tell you is that you're not supposed to make any structural changes (insertions/deletions) while iterating over the dict.

An easy way to fix this is by placing the result into a separate dictionary:

   new_dict = {}
   for patterns in dict_copy.keys():
        new_tuple = ()
        for items in range(len(patterns)):
            if patters[items] not in exclusion:
                new_tuple += (patterns[items],)
        new_dict[new_tuple] = dict_copy.get(patterns)
   dict_copy = new_dict
于 2012-11-27T21:41:38.897 回答
1

我在迭代恢复之前弹出一个键和值并插入另一个。

那不重要。迭代时不能更改数据结构。Python 的迭代器变得混乱(-:这与字典的大小无关,而是它的内容。(在其他编程语言中也是如此......)

于 2012-11-27T21:44:04.097 回答