查找字典中所有键的值的最大值

时间:2014-05-29 21:07:53

标签: python list dictionary counter

我有一个字典对象说

d = {
    '25478329': ['17647430', '376088951', '32416061', '43096205'],
    '43096205': '17647430',
    '376088951': ['17647430', '25478329', '32416061'],
    '32416061': ['17647430', '25478329']
}

我想要的是找出所有密钥发生的最大次数的值,例如在上面的词典中,答案将是'17647430'。

我做的是:

def di(d):
    a = []
    for i in d.values():
        if isinstance(i,str):
            a.append(i)
        else:
            for j in i:
                a.append(j)
    print a
    most_common,num_most_common = Counter(a).most_common(1)[0]
    print most_common,num_most_common

上述代码可以优化吗?

1 个答案:

答案 0 :(得分:3)

使用itertools.chain.from_iterable()链接值:

from collections import Counter
from itertools import chain

def di(d):
    counts = Counter(chain.from_iterable(
        [v] if isinstance(v, str) else v for v in d.itervalues()))
    return counts.most_common(1)[0]

如果是Python 3,请使用d.values()

如果您的值不是列表和字符串的混合,那么您会更好;我会做一切清单。

演示:

>>> from collections import Counter
>>> from itertools import chain
>>> def di(d):
...     counts = Counter(chain.from_iterable(
...         [v] if isinstance(v, str) else v for v in d.itervalues()))
...     return counts.most_common(1)[0]
... 
>>> d = {
...     '25478329': ['17647430', '376088951', '32416061', '43096205'],
...     '43096205': '17647430',
...     '376088951': ['17647430', '25478329', '32416061'],
...     '32416061': ['17647430', '25478329']
... }
>>> di(d)
('17647430', 4)