How to Find the Most Common Element in a Python Dictionary

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. Below is sample data.

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 statistics mode()

This example uses mode() from the statistics library. This function returns the single most common element found in the passed argument.

from statistics import mode
common_val = mode(students.values())

The above code calls in mode() from the statistics library.

The following line uses the mode() function and passes the values from the key:value pair of students as an argument. The results save to common_val.

If the contents of students.values() are output to the terminal, the following will display.

print(students.values())
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.

print(common_val)
99

This is correct!


Method 2: Use Collections.Counter

This example uses the collections library with the counter() function to keep track of each element count.

from collections import Counter 
common_val = Counter(students.values()).most_common

The above code imports Python’s built-in collections library and counter().

Next, the counter() function is called and is passed all values from the key:value pair of students as an argument. Then, most_common() is appended. The results save to common_val.

If this was output to the terminal, the following would display.

<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?

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.

[(99, 4)]

To extract the data further, use slicing ([0]) to reference the Tuple and assign the output accordingly.

value, count = Counter(students.values()).most_common(1)[0]
print(value, count)

Much clearer! The grade of 99 appears 4 times in students.

99 4

Method 3: Use For Loop and max()

This example locates the most common value in a Dictionary using a for loop and max() without importing a library.

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 tally.

Then a for loop is instantiated to loop through each key:value pair in the Dictionary students.

If v (the value) is not in the tally, then the count for is set to 0.

Otherwise, if tv (the value) is in tally, the count is increased by 1.

Once the iteration is complete, the max() function is called to get the most common value in tally and output to the terminal.

99

Method 4: Use max()

This example uses max() to retrieve the most common value in a Python dictionary. Simple, clean, efficient.

common_val = max(list(students.values()), key=list(students.values()).count)

The code above calls the max() function and passes two (2) arguments, the values of the key:value pairs of students and a List object.

If output to the terminal, these two (2) arguments contain the following.

print(list(students.values()))
print(list(students.values()).count)
[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.

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

“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