How to calculate subtotal of values of dictionary for key substring matches using dictionary comprehension

Viewed 143

I want to convert this below logic of dictionary to dictionary comprehension logic, how do I do?

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

Output:

{'chiken': 650, 'motton': 750, 'fish': 550}
4 Answers

why use a dict comp? it's doable, but it's going to be ugly.

i would just use a defaultdict

from collections import defaultdict

dict_b = defaultdict(int)

for k, v in dict_a.items():
    dict_b[k.split('_')[0]] += v

If you are sure about the order, you can use groupby from itertools:

{k: sum(x[1] for x in g) for k, g in groupby(dictA.items(), lambda x: x[0].split('_')[0])}

Example:

from itertools import groupby

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

dictB = {k: sum(x[1] for x in g) for k, g in groupby(dictA.items(), lambda x: x[0].split('_')[0])}

print(dictB)
# {'chiken': 650, 'motton': 750, 'fish': 550}

Another solution, without itertools:

dictA = {'chiken_biryani': 350, 'chiken_chilli': 300, 'motton_fry': 350, 'motton_biryani': 400, 'fish_prowns_fry': 250, 'fish_dry':300}

out = {k: sum(vv for kk, vv in dictA.items() if kk.startswith(k)) for k in set(k.split('_')[0] for k in dictA)}
print(out)

Prints:

{'chiken': 650, 'motton': 750, 'fish': 550}

You can make a set of unique keys and then iterate the dictionary summing the values when this key is found:

dictA = {'chiken_biryani': 350, 'chiken_chilli': 300, 'motton_fry': 350, 'motton_biryani': 400, 'fish_prowns_fry': 250, 'fish_dry':300}

key_list = set([item.split('_')[0] for item in dictA.keys()])

dictB = {unique_key: sum(el for key, el in dictA.items() if key.split('_')[0]==unique_key) for unique_key in key_list}

Result:

{'chiken': 650, 'motton': 750, 'fish': 550}
Related