gpt4 book ai didi

python - 如何使用字典理解计算键子字符串匹配的字典值小计

转载 作者:行者123 更新时间:2023-12-04 02:33:20 26 4
gpt4 key购买 nike

我想将下面的字典逻辑转换为字典理解逻辑,我该怎么做?

# 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 - 如何使用字典理解计算键子字符串匹配的字典值小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62957571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com