首页 > 解决方案 > 将字典的值转换为另一个字典及其计数

问题描述

我有一本字典如下:

d= {'a':['the','the','an','an'],'b':['hello','hello','or']}

我想将此字典转换为具有键值及其计数的嵌套字典,如下所示:

d = {'a':{'the':2,'an':2},'b':{'hello':2,'or':1}}

我可以按如下方式计算字典的值,但无法将值转换为具有计数的另一个字典。

length_dict = {key: len(value) for key, value in d.items()}

标签: pythondictionary

解决方案


您可以collections.Counter改用:

from collections import Counter
{k: dict(Counter(v)) for k, v in d.items()}

这将返回:

{'a': {'the': 2, 'an': 2}, 'b': {'hello': 2, 'or': 1}}

推荐阅读