在字典中查找所有键的字符串最大出现次数
我有一个字典对象,比如说:
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 个回答
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)