Python Program: Updating item counts using Counter objects
Write a Python program that creates a 'Counter' for a list of items and uses dictionary-style access to update the count of specific items.
Sample Solution:
Code:
from collections import Counter
def main():
items = ['Red', 'Green', 'Black', 'Black', 'Red', 'Red', 'Orange', 'Pink', 'Pink', 'Red', 'White']
# Create a Counter for the list of items
counter = Counter(items)
print("Original Counter:")
print(counter)
# Update the count of specific items using dictionary-style access
counter['Red'] += 2
counter['Orange'] -= 1
print("\nUpdated Counter:")
print(counter)
if __name__ == "__main__":
main()
Output:
Original Counter: Counter({'Red': 4, 'Black': 2, 'Pink': 2, 'Green': 1, 'Orange': 1, 'White': 1}) Updated Counter: Counter({'Red': 6, 'Black': 2, 'Pink': 2, 'Green': 1, 'White': 1, 'Orange': 0})
In the exercise above, the "Counter" is first created for the list of items. The count of specific items is then updated using dictionary-style access, where we provide the item as the key and the new count as the value. In order to show the changes in the counts after updating, the modified "Counter" is printed.
Flowchart:
Previous: Python Program: Calculate Jaccard Similarity Coefficient.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics