python - 如何使用字典理解计算键子字符串匹配的字典值小计
问题描述
我想将下面的字典逻辑转换为字典理解逻辑,我该怎么做?
# Example: You have this dictA as input
dictA = {'chiken_biryani': 350, 'chiken_chilli': 300, 'motton_fry': 350, 'motton_biryani': 400, 'fish_prowns_fry': 250, 'fish_dry':300}
# Q: Print the total of each category, chiken, motton and fish items sub total values, using dictionary comprehension?
# Expected Output: {'chicken': 650, 'motton': 750, 'fish': 550}
dictB = dict()
for (k,v) in dictA.items():
k = k.split('_')[0]
if dictB.get(k) is None:
dictB[k] = v
else:
dictB[k] = dictB.get(k)+v
print(dictB)
输出:
{'chiken': 650, 'motton': 750, 'fish': 550}
解决方案
为什么要使用 dict comp?这是可行的,但它会很丑。
我会用一个defaultdict
from collections import defaultdict
dict_b = defaultdict(int)
for k, v in dict_a.items():
dict_b[k.split('_')[0]] += v
推荐阅读
- python - Flask 宁静的分页
- pytest - 我们如何仅跳过特定条件但在测试函数中执行休息测试?
- docker - 在 Alpine Linux (Raspberry Pi 3) 上使用 Docker
- c++ - 在哪里将我的 c++ 程序的数据保存在 linux 文件系统中以便能够访问它?
- java - Constraints not working properly in a newer version of android studio
- php - 用 IN Laravel 的方式进行 SQL JOIN 查询
- css - How to align columns with flexbox?
- r - How to convert row names to column names and bind it by order in r
- apache-kafka - 将 Post Telemetry 消息发布到 Kafka 主题的有效负载是什么 - 协议消息解析失败
- wso2 - 高级限制适用于一台服务器,但不适用于其他服务器