Search code examples
pythonpython-3.xdictionarydictionary-comprehension

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


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}

Solution

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