按名称合并同一词典的键

  • 本文关键字:合并 python dictionary
  • 更新时间 :
  • 英文 :


假设我有一个包含以下内容的字典:

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}

我不确定我在做研究时用的词是否正确,所以提供一点帮助会很好。我必须创建一个新的dictionay并将所有以"冰淇淋"开头的关键字相加吗?

也许您可以尝试这种方法,使用defaultdictfrom collections模块来解析键作为标准,并重新创建一个新的字典。这可能会对您有所帮助:


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})

这段代码假设不同口味的甜点的键只在菜名的末尾不同,这并不能保证(例如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]

最新更新