Python 3:如何在字典中找到最常出现的值?

时间:2017-06-17 09:06:52

标签: python python-3.x loops dictionary for-loop

我正在尝试制作一个程序,当给出这样的字典时 -

    sports_played={sam:baseball,john:tennis,dan:tennis,joe:cricket,drew:tennis,mark:baseball}

应该返回网球,即最常用的运动,即dict中发生率最高的值。

如果问题有问题,请提前抱歉。这是我的第一个问题。

3 个答案:

答案 0 :(得分:2)

如果我们假设eaters是一本字典,那么:

eaters={'chicken':5,'meat':7,'rice':3} 
max(eaters.values())

结果: 7

在现实世界中,你不会使用循环来实现这一点。

eaters

中查看您可以使用的内容
dir(eaters)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

eaters.keys()
['chicken', 'rice', 'meat']
eaters.values()
[5, 3, 7]

循环版本:

x=0
for i in eaters.values():
    if i > x:
        x = i
print i
7

答案 1 :(得分:0)

如果您想获得最大元素的key,即meat,您可以使用以下代码:

>>> list(eaters.keys())[list(eaters.values()).index(max(eaters.values()))]
>>> 'meat'

答案 2 :(得分:0)

如果查看dir(dict),您会在dict class/object dict.get()内看到一个可以使用的有趣方法。

因此,如果您在python解释器中键入help(dict.get),您将获得:

  

有关method_descriptor的帮助:

     

的get(...)       D.get(k [,d]) - >如果k在D中则为D [k],否则为d。 d默认为无。

因此,基本上dict.get()会查看dict中是否存在某个键并将其设置为d值(默认为None)。

所以,我们可以这样做:

eaters = {'chicken': 5, 'meat': 5, 'rice': 3}

counts = {}
for k in eaters.values():
    # If we find the k key in counts we add 1
    # If not set the count to 1
    counts[k] = counts.get(k, 0) + 1

print(counts)

>>> {3: 1, 5: 2}

所以,我们有一个词典,其中我们计算每个食客的dict值的出现次数。

最后,为了获得eaters dict值的最大值,我们可以做到:

# get_max: temporar variable in which we stock the max
# val = will stock the key with the max value in counts dict
get_max, val = 0, 0
for k, v in counts.items():
    if v > get_max:
        get_max = v
        val = k
print(k)

>>> 5