How to Count the Number of Occurrences within a Python Dictionary

How to Count the Number of Occurrences within a Python Dictionary

Python Tip: To count the number of occurrences within a Python dictionary, use Counter from the collections module.

Heres an example 👇

from collections import Counter

devices_vendors = {
    'device001': 'Cisco', 
    'device002': 'Juniper', 
    'device003': 'Cisco',
    'device004': 'Arista',
    'device005': 'Cisco'
}

vendor_counts = Counter(devices_vendors.values())

print(vendor_counts) 
# Output: 
# Counter({'Cisco': 3, 'Juniper': 1, 'Arista': 1})

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!