[英]A way to compare dictionary values in python and printing their keys
I have written the following code: 我写了以下代码:
dict = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}
biggestKey = max([[dict[key],key] for key in dict])[1]
print(biggestKey)
From this I get the result: 从这里我得到了结果:
dog
狗
Whereas I actually want to get: 虽然我真的想得到:
dog;cat
狗猫
How can I fix the code? 我该如何修复代码?
If you want to find all the keys which have the same maximum value, you can do: 如果要查找具有相同最大值的所有键,可以执行以下操作:
>>> 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']
You can just filter out the keys that have the max value: 您只需过滤掉具有最大值的键:
>>> d = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}
>>> print([k for k, v in d.items() if v == max(d.values())})
['dog', 'cat']
Or even with a collections.defaultdict
: 甚至使用
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']
One way is to use list comprehension: 一种方法是使用列表理解:
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']
d = {} d = {}
This will do the trick: max(d, key=d.get)
这样就可以了:
max(d, key=d.get)
Also: max(d.values())
另外:
max(d.values())
Try this : 尝试这个 :
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)))
output: 输出:
['cat', 'dog']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.