Counting the frequencies in a list using dictionary in Python
Given an unsorted list of some elements(may or may not be integers), Find the frequency of each distinct element in the list using a dictionary.
Example:
The problem can be solved in many ways. A simple approach would be to iterate over the list and use each distinct element of the list as a key of the dictionary and store the corresponding count of that key as values. Below is the Python code for this approach:
# Python program to count the frequency of
# elements in a list using a dictionary
def CountFrequency(my_list):
# Creating an empty dictionary
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
print ("% d : % d"%(key, value))
# Driver function
if __name__ == "__main__":
my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
CountFrequency(my_list)
|
Time Complexity:O(N), where N is the length of the list.
Alternative way: An alternative approach can be to use the list.count() method.
# Python program to count the frequency of
# elements in a list using a dictionary
def CountFrequency(my_list):
# Creating an empty dictionary
freq = {}
for items in my_list:
freq[items] = my_list.count(items)
for key, value in freq.items():
print ("% d : % d"%(key, value))
# Driver function
if __name__ == "__main__":
my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
CountFrequency(my_list)
|
Time Complexity:O(N2), where N is the length of the list. The time complexity list.count() is O(N) alone, and when used inside loop it will become O(N2).
Alternative way:An alternative approach can be to use the dict.get() method. This makes the program much more shorter and makes understand how get method is useful instead of if…else.
# Python program to count the frequency of
# elements in a list using a dictionary
def CountFrequency(my_list):
# Creating an empty dictionary
count = {}
for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1 ,4, 4, 4, 2, 2, 2, 2]:
count[i] = count.get(i, 0) + 1
return count
# Driver function
if __name__ == "__main__":
my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
print(CountFrequency(my_list))
|
Related Article :
Count frequencies of all elements in array in Python using collections module
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Dictionaries
A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the indices can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.
As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict() >>> print(eng2sp) {}The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:
>>> eng2sp['one'] = 'uno'This line creates an item that maps from the key 'one' to the value “uno”. If we print the dictionary again, we see a key-value pair with a colon between the key and value:
>>> print(eng2sp) {'one': 'uno'}This output format is also an input format. For example, you can create a new dictionary with three items. But if you print eng2sp, you might be surprised:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print(eng2sp) {'one': 'uno', 'three': 'tres', 'two': 'dos'}The order of the key-value pairs is not the same. In fact, if you type the same example on your computer, you might get a different result. In general, the order of items in a dictionary is unpredictable.
But that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values:
>>> print(eng2sp['two']) 'dos'The key 'two' always maps to the value “dos” so the order of the items doesn’t matter.
If the key isn’t in the dictionary, you get an exception:
>>> print(eng2sp['four']) KeyError: 'four'The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp) 3The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary (appearing as a value is not good enough).
>>> 'one' in eng2sp True >>> 'uno' in eng2sp FalseTo see whether something appears as a value in a dictionary, you can use the method values, which returns the values as a type that can be converted to a list, and then use the in operator:
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a linear search algorithm. As the list gets longer, the search time gets longer in direct proportion to the length of the list. For dictionaries, Python uses an algorithm called a hash table that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a dictionary. I won’t explain why hash functions are so magical, but you can read more about it at wikipedia.org/wiki/Hash_table.
Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt
Write a program that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.
That One Thing
Create a Dictionary From a List
Count the number of times an item appears in a Python list, with code examples
You know that road-trip game, where you only count cars you see if they are of the same color. On a long, lonely stretch of road, it is a game of anticipation. On a busy highway, it can get a bit neurotic. Sometimes, the game can…