我的代码中出现 keyerror 1

keyerror 1 in my code

我正在编写一个函数,该函数接受字典输入和 return 在该字典中具有唯一值的键列表。考虑一下,

ip = {1: 1, 2: 1, 3: 3}

所以输出应该是 [3],因为键 3 具有唯一值,字典中不存在。

现在给定的功能有问题:

def uniqueValues(aDict):

    dicta = aDict
    dum = 0
    for key in aDict.keys():

        for key1 in aDict.keys():

            if key == key1:
                dum = 0
            else:
                if aDict[key] == aDict[key1]:
                    if key in dicta:
                        dicta.pop(key)
                    if key1 in dicta:
                        dicta.pop(key1)

    listop = dicta.keys()
    print listop
    return listop

我收到如下错误:

File "main.py", line 14, in uniqueValues if aDict[key] == aDict[key1]: KeyError: 1

我哪里做错了?

你的主要问题是这一行:

dicta = aDict

你认为你正在制作字典的副本,但实际上你仍然只有一本字典,所以对 dicta 的操作也会改变 aDict(因此,你从 adict 中删除值,它们也会从 aDict 中删除,所以你得到了你的KeyError)。

一个解决方案是

dicta = aDict.copy()

(你也应该给你的变量起更清晰的名字,让你自己更清楚自己在做什么)

(edit) 此外,还有一种更简单的方法来完成您正在做的事情:

def iter_unique_keys(d):
    values = list(d.values())
    for key, value in d.iteritems():
        if values.count(value) == 1:
            yield key

print list(iter_unique_keys({1: 1, 2: 1, 3: 3}))

使用 Counter 来自 collections 库:

from collections import Counter

ip = {
    1: 1,
    2: 1,
    3: 3,
    4: 5,
    5: 1,
    6: 1,
    7: 9
}

# Generate a dict with the amount of occurrences of each value in 'ip' dict
count = Counter([x for x in ip.values()])

# For each item (key,value) in ip dict, we check if the amount of occurrences of its value.
# We add it to the 'results' list only if the amount of occurrences equals to 1. 
results = [x for x,y in ip.items() if count[y] == 1]

# Finally, print the results list
print results

输出:

[3, 4, 7]