dict.copy中的Python KeyError

时间:2019-02-06 05:04:56

标签: python

我的功能:

def adjustDict(d):
    new = {}
    for word in d:
        lword = word.lower()
        possible = getPossible(lword)
        new[lword] = new.get(lword, 0) + d[word]
        for pword in possible:
            new[pword] = new.get(pword, 0) + d.get(pword, 0)
    nnew = new.copy()
    for word in nnew:
        print(word, word in new, word in nnew)
        if new[word] == 0: # KeyError
            del new[word]
        else:
            possible = getPossible(word)
            max_freq = max([new.get(pword, 0) for pword in possible] + [new[word]])
            for pword in possible:
                if 0 < new.get(pword, 0) < max_freq:
                    del new[pword]
    return new

我在注释行中得到了KeyError,我认为这不应该发生,因为nnew只是new的副本。 Why does a key appear in the copy of a dict but not the dict itself?我没有做任何与异步有关的事情。

这是错误消息:

kazan's True True
kazan True True
kazan' True True
early True True
ear True True
earle False True
Traceback (most recent call last):
  File "C:\Users\Seaky\Desktop\Docs\UCSB\3rd\2019 Winter\CS 165A\MP1\main.py", line 102, in <module>
    write('training_pos.json', adjustDict(readJson('training_pos.json')))
  File "C:\Users\Seaky\Desktop\Docs\UCSB\3rd\2019 Winter\CS 165A\MP1\main.py", line 52, in adjustDict
    if new[word] == 0:
KeyError: 'earle'

0 个答案:

没有答案