Counting the occurrences of elements in a dictionary allows you to determine the frequency of specific values in the dictionary. In this blog post, we will explore different methods to count the occurrences of elements in a dictionary in Python.
Method 1: Using a loop and a counter
# Method 1: Using a loop and a counter my_dict = {"a": 1, "b": 2, "c": 2, "d": 3, "e": 1} count_dict = {} for value in my_dict.values(): count_dict[value] = count_dict.get(value, 0) + 1 print("Occurrences:", count_dict)
Output:
Occurrences: {1: 2, 2: 2, 3: 1}
Method 2: Using the collections module
# Method 2: Using the collections module import collections my_dict = {"a": 1, "b": 2, "c": 2, "d": 3, "e": 1} count_dict = collections.Counter(my_dict.values()) print("Occurrences:", count_dict)
Output:
Occurrences: Counter({1: 2, 2: 2, 3: 1})