2017-07-08 334 views
1

如果我有一本字典找到python字典中所有最大值的键?

x ={0: 0, 1: 4, 2: 0, 3: 2, 4: 2, 5: 4} 

我如何得到所有的最大值

在这种情况下的钥匙,他们将在1和5。

不是重复的问题。寻找所有的钥匙,而不只是一个。

+0

看看[这个答案](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) – Tim510

+1

我做到了。但那是找到最大的。所以它只返回1而不是5. – aditmohan96

+0

这里的非平凡情况 –

回答

1

collections中有一门课叫做Counter,它完全符合你的要求。它提供给你通过它需要的具体功能是most_common方法:

from collections import counter 
maxes = Counter(x).most_common(2) 
print([x[0] for x in maxes]) 

[1, 5] 

现在,这可能不是你想要什么,因为我很难在数字2的编码可以通过使用得到这个另一个Counter您的字典的值!

x = Counter(x) # This preserves x: just makes it a subclass of dict 
max_count = Counter(x.values())[x.most_common(1)[0][1]] 
maxes = x.most_common(max_count) 
maxes = [x[0] for x in maxes] 

在这里,我算得通过计数所有不同的值,然后检查使用x.most_common(1)[0][1]中最大的一个,经常发生的值的次数。

请不要选择这个答案。 @BrightOne有正确的答案。这只是我做过的一件事,看看我是否可以避免使用除计数器之外的任何东西。这实际上并不是一个好主意。

3
x ={0: 0, 1: 4, 2: 0, 3: 2, 4: 2, 5: 4} 

maximum = max(x.values()) 
keys = [key for key, value in x.items() if value == maximum] 
print(keys) # => [1, 5] 
+0

这比我的回答要复杂得多。 –

+0

我唯一的建议是为了可读性而在理解中解开元组:'[key for key,value in x.items()if value == maximum]' –

+0

@MadPhysicist谢谢你,它好多了!编辑。 – BrightOne