Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Find the Most Common Element in a Python Dictionary
1
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]

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}

[Image: 1f4ac.png] 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
Code:
mode()
from the
Code:
statistics
library. This function returns the single most common element found in the passed argument.

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

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

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

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

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!

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Method 2: Use Collections.Counter

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

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

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

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

If 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])
to reference the Tuple and assign the output accordingly.

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

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

99 4

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Method 3: Use For Loop and max()

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

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

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

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

Otherwise, if t
Code:
v
(the value) is in tally, the count is increased by 1.

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

99

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Method 4: Use max()

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

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

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

If 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

[Image: image-31.png][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]
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: