w3resource

Python: Combine values in python list of dictionaries

Python dictionary: Exercise-23 with Solution

Write a Python program to combine values in a list of dictionaries.

Sample Solution:

Python Code:

# Import the 'Counter' class from the 'collections' module.
from collections import Counter

# Create a list 'item_list' containing dictionaries with 'item' and 'amount' as keys.
item_list = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]

# Create an empty Counter object 'result' to store the summed amounts for each 'item'.
result = Counter()

# Iterate through the dictionaries in 'item_list' using a for loop.
for d in item_list:
    # Update the 'result' Counter by adding the 'amount' to the corresponding 'item' key.
    result[d['item']] += d['amount']

# Print the 'result' Counter, which contains the summed amounts for each 'item'.
print(result) 
 

Sample Output:

Counter({'item1': 1150, 'item2': 300})

Python Code Editor:

Previous: Write a Python program to find the highest 3 values of corresponding keys in a dictionary.
Next: Write a Python program to create a dictionary from a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.