一种比较python中的字典值并打印其键的方法

时间:2018-01-24 14:29:10

标签: python for-loop

我写了以下代码:

dict = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}

biggestKey = max([[dict[key],key] for key in dict])[1]

print(biggestKey)

从此我得到了结果:

  

我真的想得到:

  

狗;猫

如何修复代码?

5 个答案:

答案 0 :(得分:1)

如果要查找具有相同最大值的所有键,可以执行以下操作:

>>> D = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}
>>> maxval = max(D.values())
>>> [k for k, v in D.items() if v == maxval]
['cat', 'dog']

答案 1 :(得分:1)

您可以过滤掉具有最大值的键:

>>> d = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}
>>> print([k for k, v in d.items() if v == max(d.values())})
['dog', 'cat']

甚至使用collections.defaultdict

from collections import defaultdict
from operator import itemgetter

d = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}

dic = defaultdict(list)
for key, value in d.items():
    dic[value].append(key)

print(max(dic.items(), key = itemgetter(0))[1])
# ['dog', 'cat']

答案 2 :(得分:1)

一种方法是使用列表理解:

my_dict = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}

my_keys = [k for k in my_dict if my_dict[k] == max(my_dict.values())]

# returns ['dog', 'cat']

答案 3 :(得分:0)

d = {}

这样可以解决问题:max(d, key=d.get)

另外:max(d.values())

答案 4 :(得分:0)

试试这个:

dict_1 = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}

from collections import defaultdict

d=defaultdict(list)

for j,i in dict_1.items():
    d[i].append(j)

print(d.get(max(d)))

输出:

['cat', 'dog']