在 Python 字典中查找最频繁的值(具有最大计数的值)

Mar*_*ube 4 python dictionary

我正在尝试编写一个函数,该函数返回 Python 字典中最频繁的值。我不想导入任何东西,只是简单的代码。

有任何想法吗?例如,如果我的字典是:

input_dict = {'A': 1963, 'B': 1963, 
    'C': 1964, 'D': 1964, 'E': 1964,
    'F': 1965, 'G': 1965, 'H': 1966,
    'I': 1967, 'J': 1967, 'K': 1968,
    'L': 1969 ,'M': 1969,
    'N': 1970}
Run Code Online (Sandbox Code Playgroud)

预期结果是1964 (因为它作为dict3 次(最大计数)中的值出现)

这是我最后一次尝试:

def most_prolific(input_dict):

    values = []
    for year in input_dict.values():
        if year in input_dict.values():
            values.append(year)


    for most in values:
        if most in values:
         return max(values.count(most))
Run Code Online (Sandbox Code Playgroud)

Moi*_*dri 8

使用collections.Counter

实现这一点的最简单方法是使用 Python 的内置collections.Counter函数,它是为相同目的而创建的。以下是您的示例的示例代码:

from collections import Counter 
input_dict = {'A': 1963, 'B': 1963, 'C': 1964, 'D': 1964, 'E': 1964, 'F': 1965, 'G': 1965, 'H': 1966, 'I': 1967, 'J': 1967, 'K': 1968, 'L': 1969 ,'M': 1969, 'N': 1970}

value, count = Counter(input_dict.values()).most_common(1)[0]
# in above code, `value` will hold value `1964`  <--- one you desire
#            and `count` will hold value `3`
Run Code Online (Sandbox Code Playgroud)

使用中间字典(没有导入)

这是另一个没有导入任何模块的。在这里,我使用以下方式创建自己的计数器dict

my_counter_dict = {}
for v in input_dict.values():
    my_counter_dict[v] = my_counter_dict.get(v, 0)+1

# Value hold by `my_counter_dict`:
#  {1963: 2, 1964: 3, 1965: 2, 1966: 1, 1967: 2, 1968: 1, 1969: 2, 1970: 1}
Run Code Online (Sandbox Code Playgroud)

从上面dict,使用max函数提取具有最大值的键:

>>> max(my_counter_dict.iterkeys(), key=my_counter_dict.get)
1964
Run Code Online (Sandbox Code Playgroud)

不使用中间字典(没有导入)

这是另一种不创建中间字典的替代方法,但由于列表中的list.count每个元素都进行了一次完整的列表迭代,因此效率相对较低:

>>> values_list = list(input_dict.values())
>>> max(set(values_list), key=values_list.count)
1964
Run Code Online (Sandbox Code Playgroud)


Aad*_*Ura 7

即使我建议你不需要导入任何东西,它的简单任务:

input_dict = {'A': 1963, 'B': 1963,
    'C': 1964, 'D': 1964, 'E': 1964,
    'F': 1965, 'G': 1965, 'H': 1966,
    'I': 1967, 'J': 1967, 'K': 1968,
    'L': 1969 ,'M': 1969,
    'N': 1970}


track={}

for key,value in input_dict.items():
    if value not in track:
        track[value]=0
    else:
        track[value]+=1

print(max(track,key=track.get))
Run Code Online (Sandbox Code Playgroud)

输出:

1964
Run Code Online (Sandbox Code Playgroud)