09-09-2022, 12:16 PM
How to Find the Most Common Element in a Python Dictionary
5/5 – (1 vote)
Problem Formulation and Solution Overview
This article will show you how to find the most common element in a Python Dictionary. However, since all Dictionary Keys are unique, this article focuses on searching for the most common Dictionary Value.
To make it more fun, we have the following running scenario:
Marty Smart, a Math Teacher at Harwood High, has amassed his student’s grades for the semester and has come to you to write a script to determine the most common grade. [i]Below is sample data.[/i]
Question: How would we write code to locate the most common value in a Dictionary?
We can accomplish this task by one of the following options:
Method 1: Use statistics mode()
This example uses from the library. This function returns the single most common element found in the passed argument.
The above code calls in from the statistics library.
The following line uses the function and passes the values from the key:value pair of as an argument. The results save to .
If the contents of are output to the terminal, the following will display.
Run the code below to find the most common value.
99
This is correct!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqX0qqEVpP5s%2Fhqdefault.jpg)
Method 2: Use Collections.Counter
This example uses the library with the function to keep track of each element count.
The above code imports Python’s built-in library and .
Next, the function is called and is passed all values from the key:value pair of as an argument. Then, is appended. The results save to .
If this was output to the terminal, the following would display.
This isn’t the result we want. How can we get this result?
If we append a (1) to the end of most_common, a List containing one Tuple returns.
To extract the data further, use slicing ( to reference the Tuple and assign the output accordingly.
Much clearer! The grade of 99 appears 4 times in.
99 4
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD2i-SmUELJI%2Fhqdefault.jpg)
Method 3: Use For Loop and max()
This example locates the most common value in a Dictionary using a loop and without importing a library.
The above code declares an empty Dictionary.
Then a loop is instantiated to loop through each key:value pair in the Dictionary .
If(the value) is not in the , then the count for is set to 0.
Otherwise, if t (the value) is in tally, the count is increased by 1.
Once the iteration is complete, the function is called to get the most common value in and output to the terminal.
99
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcAK34XhOkI8%2Fhqdefault.jpg)
Method 4: Use max()
This example uses to retrieve the most common value in a Python dictionary. Simple, clean, efficient.
The code above calls the function and passes two (2) arguments, the values of the key:value pairs of and a object.
If output to the terminal, these two (2) arguments contain the following.
To retrieve the most common element, run the following code.
99
Summary
This article has provided four (4) ways to find the most common element in a Python Dictionary. These examples should give you enough information to select the best fitting for your coding requirements.
Good Luck & Happy Coding!
Programmer Humor – Blockchain
[i]“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source – xkcd[/i]
5/5 – (1 vote)
Problem Formulation and Solution Overview
This article will show you how to find the most common element in a Python Dictionary. However, since all Dictionary Keys are unique, this article focuses on searching for the most common Dictionary Value.
To make it more fun, we have the following running scenario:
Marty Smart, a Math Teacher at Harwood High, has amassed his student’s grades for the semester and has come to you to write a script to determine the most common grade. [i]Below is sample data.[/i]
Code:
students = {'Marc': 99, 'Amie': 76, 'Jonny': 98, 'Anne': 99, 'Andy': 77, 'Elli': 98, 'Acer': 67, 'Joan': 61, 'Mike': 54, 'Anna': 76, 'Bobi': 67, 'Kate': 99, 'Todd': 98, 'Emma': 49, 'Stan': 76, 'Harv': 99, 'Ward': 67, 'Hank': 54, 'Wendy': 98, 'Sven': 100}
Question: How would we write code to locate the most common value in a Dictionary?We can accomplish this task by one of the following options:
- Method 1: Use Code:
statistics.mode()
- Method 2: Use Code:
collections.Counter
- Method 3: Use loop andCode:
forCode:max()
- Method 4: Use Code:
max()
Method 1: Use statistics mode()
This example uses
Code:
mode()Code:
statisticsCode:
from statistics import mode
common_val = mode(students.values())The above code calls in
Code:
mode()The following line uses the
Code:
mode()Code:
studentsCode:
common_valIf the contents of
Code:
students.values()Code:
print(students.values())Code:
dict_values([99, 76, 98, 99, 77, 98, 67, 61, 54, 76, 67, 99, 98, 49, 76, 99, 67, 54, 98, 100])Run the code below to find the most common value.
Code:
print(common_val)99
This is correct!
Method 2: Use Collections.Counter
This example uses the
Code:
collectionsCode:
counter()Code:
from collections import Counter common_val = Counter(students.values()).most_commonThe above code imports Python’s built-in
Code:
collectionsCode:
counter()Next, the
Code:
counter()Code:
studentsCode:
most_common()Code:
common_valIf this was output to the terminal, the following would display.
Code:
<bound method Counter.most_common of Counter({99: 4, 98: 4, 76: 3, 67: 3, 54: 2, 77: 1, 61: 1, 49: 1, 100: 1})>This isn’t the result we want. How can we get this result?
Code:
common_val = Counter(students.values()).most_common(1)If we append a (1) to the end of most_common, a List containing one Tuple returns.
Code:
[(99, 4)]To extract the data further, use slicing (
Code:
[0])Code:
value, count = Counter(students.values()).most_common(1)[0]
print(value, count)Much clearer! The grade of 99 appears 4 times in
Code:
students99 4
Method 3: Use For Loop and max()
This example locates the most common value in a Dictionary using a
Code:
forCode:
max()Code:
tally = {}
for k, v in students.items(): if v not in tally: tally[v] = 0 else: tally[v] += 1
print(max(tally, key=tally.get))The above code declares an empty Dictionary
Code:
tallyThen a
Code:
forCode:
studentsIf
Code:
vCode:
tallyOtherwise, if t
Code:
vOnce the iteration is complete, the
Code:
max()Code:
tally99
Method 4: Use max()
This example uses
Code:
max()Code:
common_val = max(list(students.values()), key=list(students.values()).count)The code above calls the
Code:
max()Code:
studentsCode:
ListIf output to the terminal, these two (2) arguments contain the following.
Code:
print(list(students.values()))
print(list(students.values()).count)Code:
[99, 76, 98, 99, 77, 98, 67, 61, 54, 76, 67, 99, 98, 49, 76, 99, 67, 54, 98, 100]<built-in method count of list object at 0x00000239566D3540>To retrieve the most common element, run the following code.
Code:
print(common_val)99
Summary
This article has provided four (4) ways to find the most common element in a Python Dictionary. These examples should give you enough information to select the best fitting for your coding requirements.
Good Luck & Happy Coding!
Programmer Humor – Blockchain
[i]“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source – xkcd[/i]

