python - 将字典的值转换为另一个字典及其计数
问题描述
我有一本字典如下:
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()}
解决方案
您可以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}}
推荐阅读
- python - pygame不注册键输入
- javascript - 未处理的承诺拒绝:错误:无权使用后台定位服务
- postman - 表单参数“我的密钥”,文件加载错误:缺少文件源 - 邮递员
- ios - 具有透明背景的 iOS 扩展
- python - Pandas datframe excel错误
- python - 尝试解释 XGBoost 分类器的权重时出现 TypeError
- java - java - 如何接收通过Node-red发送到Java中的Reactor UdpClient / UdpServer的udp数据包?
- c# - MongoDB不会让我保存对象可能的循环引用
- npm - npm 详细堆栈错误:无法验证,需要:基本领域 =“https://npm.fontawesome.com/”,服务 =“npm.fontawesome.com”
- javascript - SharePoint Online API - 检测 NoScript (DenyAddAndCustomizePages) 状态?