[英]Merge Key of the same Dictionary by their name
假设我有一本包含以下内容的字典:
Dessert = {'cake': 71,
'Crumble': 53,
'ice cream Chocolate': 23,
'ice cream Vanilla': 15,
'ice cream Strawberry': 9,
'ice cream Mint chocolate': 8}
如何对以相同方式开始的键进行分组? 我想得到这样的东西:
Dessert = {'cake': 71,
'Crumble': 53,
'ice cream': 55}
我不确定我在进行研究时是否使用了正确的词,所以有一点帮助会很好。 我是否必须创建一个新字典并将所有以“冰淇淋”开头的键相加?
此代码假定甜点的不同口味的键仅在菜名的末尾有所不同,这不能保证(例如ice cream Mint chocolate
它会失败),但这是我能想到的最好的和。
simplified_dessert = dict()
core_dish = ''
for dish_name in dessert:
if word:
if dish_name.split()[:-1] == core_dish:
simplified_dessert[core_dish] += dessert[dish_name]
else:
word = dish_name.split()[:-1]
simplified_dessert[core_dish] = dessert[dish_name]
也许您可以尝试这种方法,方法是使用 collections 模块中的defaultdict将键解析为条件并重新创建一个新字典。 这可能会帮助您:
from collections import defaultdict
ddc = defaultdict(int)
for key, val in Dessert.items():
if key.startswith('ice'):
key = key.split()[:2] # extract "ice cream' as key
ddc[' '.join(key)] += val
else:
ddc[key] += val
print(ddc)
defaultdict(<class 'int'>, {'cake': 71, 'Crumble': 53, 'ice cream': 55})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.