Home > database >  Merge Key of the same Dictionary by their name
Merge Key of the same Dictionary by their name

Time:08-24

Let's say that I have a dictionary that contains the following:

Dessert = {'cake': 71,
 'Crumble': 53,
 'ice cream Chocolate': 23,
 'ice cream Vanilla': 15,
 'ice cream Strawberry': 9,
 'ice cream Mint chocolate': 8}

how can I group keys that start in the same way ? I would like to get something like this:

Dessert = {'cake': 71,
 'Crumble': 53,
 'ice cream': 55}

I'm not sure I'm using the right words when I do my research so a little help would be nice. Do I have to create a new dictionay and sum all the keys starting with 'ice cream'?

CodePudding user response:

This code assumes that the keys of the different flavours of the desserts only differ at the end of the dish's name, which isn't guaranteed (for example it'll fail for ice cream Mint chocolate), but it's the best I could come up with.

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]

CodePudding user response:

Maybe you can try this approach by using the defaultdict from collections module to parse the key as the criteria and recreate a new dictionary. This might help you:


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)

Output:

defaultdict(<class 'int'>, {'cake': 71, 'Crumble': 53, 'ice cream': 55})
  • Related