Python 我的代码中的 keyerror 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33800004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:00:47  来源:igfitidea点击:

keyerror 1 in my code

pythonkeyerror

提问by rajesh padgilwar

I am writing a function that take dictionary input and return list of keys which have unique values in that dictionary. Consider,

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

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

so output should be [3] as key 3 has unique value which is not present in dict.

所以输出应该是 [3] 因为键 3 有唯一的值,这在 dict 中不存在。

Now there is problem in given fuction:

现在给定函数存在问题:

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

I am getting error like:

我收到如下错误:

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

文件“main.py”,第 14 行,在 uniqueValues 如果 aDict[key] == aDict[key1]: KeyError: 1

Where i am doing wrong?

我哪里做错了?

采纳答案by Emile

Your main problem is this line:

您的主要问题是这一行:

dicta = aDict

You think you're making a copy of the dictionary, but actually you still have just one dictionary, so operations on dicta also change aDict (and so, you remove values from adict, they also get removed from aDict, and so you get your KeyError).

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

One solution would be

一种解决方案是

dicta = aDict.copy()

(You should also give your variables clearer names to make it more obvious to yourself what you're doing)

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

(edit) Also, an easier way of doing what you're doing:

(编辑)另外,一种更简单的方式来做你正在做的事情:

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

回答by Andrés Pérez-Albela H.

Use Counterfrom collectionslibrary:

Countercollections库中使用:

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

Output:

输出:

[3, 4, 7]