Skip to main content
 首页 » 编程设计

python之字典中出现次数最多的值

2025年05月04日9tintown

我有以下字典:

d = {"a":["MRS","VAL"],"b":"PRS","c":"MRS","d":"NTS"} 

我想创建一个字典,给出每个值的出现。基本上,它看起来像:

output = {"MRS":2,"PRS":1,"NTS":1,"VAL":1} 

有谁知道我该怎么做? 提前致谢 !

请您参考如下方法:

由于您的字典由字符串和字符串列表组成,因此您首先需要 flatten将这些元素转换为常见类型的字符串:

import collections 
d = {"a":["MRS","VAL"],"b":"PRS","c":"MRS","d":"NTS"} 
 
def flatten(l): 
    for el in l: 
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring): 
            for sub in flatten(el): 
                yield sub 
        else: 
            yield el 
 
>>> list(flatten(d.values())) 
['MRS', 'VAL', 'MRS', 'PRS', 'NTS'] 

然后你可以使用 Counter计算每个字符串的出现次数:

>>> collections.Counter(flatten(d.values()))  
Counter({'MRS': 2, 'NTS': 1, 'PRS': 1, 'VAL': 1})