字典中最常见的值

Jb_*_*Eyd 1 python sorting dictionary

我有以下字典:

d = {"a":["MRS","VAL"],"b":"PRS","c":"MRS","d":"NTS"}
Run Code Online (Sandbox Code Playgroud)

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

output = {"MRS":2,"PRS":1,"NTS":1,"VAL":1}
Run Code Online (Sandbox Code Playgroud)

有谁知道我怎么能这样做?提前致谢 !

daw*_*awg 7

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

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']
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用计数器来计算每个字符串的出现次数:

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