Counting Using Dictionaries
tags: #python/documentation/dictionaries
Given an unsorted sequence of items, we can find the frequency of each distinct element in a sequence using a dictionary.
This can be done by iterating over the sequence and use each distinct element of the sequence as a key of the dictionary and store the corresponding count of that key as values. This can be done using the get() method.
Example: Occurrence of Characters in a String
word = 'brontosaurus'
d = dict()
for char in word:
d[char] = d.get(char,0) + 1
print(d)
In this example:
dis used to count the occurrences of each character in the string inword.- The
get()method is employed to retrieve the current count of each character in the dictionary, and if the character is not already a key in the dictionary, it returns 0 as the default value. - The
+1is used to increment the count of each character in the dictionary.
Example: Occurrence of Items in a List
The same concept can be applied to other objects (e.g., lists):
my_list = [1, 2, 3, 1, 2, 3, 4, 5, 1, 2]
count_dict = {}
for item in my_list:
count_dict[item] = count_dict.get(item, 0) + 1
print(count_dict)
This code will count the occurrences of each unique item in the list and store the counts in a dictionary (count_dict). The keys of the dictionary will be the unique items in the list, and the values will be their respective counts.
{1: 3, 2: 3, 3: 2, 4: 1, 5: 1}