def uniq(x, k):
for key in x:
if (x.get(key) == x.get(k)):
if (x.get(key) == x.get(k)):
return False
return True
# Testing
d1 = {'a': 1, 'b': 2, 'c': 2, 'd': 4}
k = 'a'
x = uniq(d1, k)
print(x)
我想知道如何两次检查if语句。如果字典中有重复的值,我需要找出参数键k。该函数的输出在键“ a”处应为True,在“ c”处应为False。
答案 0 :(得分:1)
要检查字典中是否有重复值,可以使用collections.Counter
:
from collections import Counter
def uniq(x, k):
count = Counter(x.values())
return count[x[k]] == 1
# Testing
d1 = {'a': 1, 'b': 2, 'c': 2, 'd': 4}
k = 'a'
x = uniq(d1, k)
print(x)
# True
您要计算每个值的出现次数,然后检查所需值是否出现1次以上