代码中的KeyError 1

11 投票
2 回答
151983 浏览
提问于 2025-05-10 15:06

我正在写一个函数,这个函数接收一个字典作为输入,然后返回这个字典中值唯一的键的列表。比如,

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

我遇到了这样的错误:

文件 "main.py",第 14 行,在 uniqueValues if aDict[key] == aDict[key1]: KeyError: 1

我哪里出错了?

相关文章:

  • 暂无相关问题
暂无标签

2 个回答

0

使用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]
8

你主要的问题出在这一行:

dicta = aDict

你以为自己在复制一个字典,但实际上你还是只有一个字典。所以对这个字典的操作也会影响到另一个字典(比如,你从adict中删除了某个值,它也会从aDict中被删除,这样就会出现KeyError错误)。

一个解决办法是:

dicta = aDict.copy()

(你还应该给你的变量起个更清晰的名字,这样能让你更容易理解自己在做什么)

(补充)还有一种更简单的方法来实现你正在做的事情:

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}))

撰写回答