我正在编写一个函数,它接受字典输入并返回在该字典中具有唯一值的键列表。考虑一下
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
我做错什么了?
使用
collections
库中的Counter
输出:
你的主要问题是这一行:
您认为您正在复制字典,但实际上您仍然只有一个字典,因此对dicta的操作也会更改aDict(因此,您从aDict中移除值,它们也会从aDict中移除,因此您会得到KeyError)。
一个解决办法是
(你也应该给你的变量更清晰的名字,让你自己更清楚地知道你在做什么)
(编辑)还有一种更简单的方法:
相关问题 更多 >
编程相关推荐