-1

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'?

  • if all the keys are good spelling yo can iter over the keys of the dict and use conditionals to add any case to your counter – WhiteAB Aug 22 '22 at 14:02
  • You might want to look at a prefix tree (or trie) https://en.wikipedia.org/wiki/Trie. And for a python specific package that might help, you can look at [pygtrie](https://pypi.org/project/pygtrie/). – Soof Golan Aug 22 '22 at 14:02
  • What is the minimum similarity you would want? I ask this because say it was if only one letter has the same index and value, then cake and crumble would be absorbed. Do you want to check at each space? – Hhadley Aug 22 '22 at 14:03

2 Answers2

0

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]
omermikhailk
  • 116
  • 6
0

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})
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23