我的代码中的关键错误1

2024-09-29 01:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

现在给定的函数有问题:

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

我做错什么了?


Tags: key函数in列表forif字典keys
2条回答

使用collections库中的Counter

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]

你的主要问题是这一行:

dicta = aDict

您认为您正在复制字典,但实际上您仍然只有一个字典,因此对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}))

相关问题 更多 >