【发布时间】:2020-11-07 11:20:20
【问题描述】:
我想将下面的字典逻辑转换为字典理解逻辑,我该怎么做?
# 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}
【问题讨论】:
标签: python python-3.x dictionary dictionary-comprehension