Thanks to visit codestin.com
Credit goes to www.geeksforgeeks.org

Open In App

Dictionary and Counter in Python to Find Winner Of Election

Last Updated : 13 Nov, 2025
Comments
Improve
Suggest changes
16 Likes
Like
Report

Given a list of votes where each element represents a vote for a candidate, the task is to determine the winner of the election. If multiple candidates receive the same number of maximum votes, the candidate with the lexicographically smaller name should be declared the winner.

For Example: 

Input: [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" ]
Output: John
Explanation: Candidates are ['john', 'johnny', 'jamie', 'jackie']
'john' and 'johnny' have the maximum votes, but 'john' is lexicographically smaller.

Let's explore different methods to find winner of Election in Python.

Using Counter

This method counts all votes using Counter and selects the candidate with the highest count, resolving ties by sorting names.

Python
from collections import Counter
votes = ['john','johnny','jackie','johnny','john','jackie', 'jamie','jamie','john','johnny','jamie','johnny','john']
c = Counter(votes)
m = max(c.values())
w = [i for i in c if c[i] == m]
print(sorted(w)[0])

Output
john

Explanation:

  • Counter(votes): counts votes for each candidate.
  • max(c.values()): finds the maximum votes.
  • List comprehension + sorted(): resolves tie lexicographically.

Using Dictionary and Counter Mapping

This method uses Counter to count votes and an extra dictionary to group candidates by vote count, helping to easily find and handle ties.

Python
from collections import Counter
votes = ['john','johnny','jackie','johnny','john','jackie','jamie','jamie','john','johnny','jamie','johnny','john']
c = Counter(votes)
d = {} 

for v in c.values():
    d[v] = []
for k, v in c.items():
    d[v].append(k)

mx = sorted(d.keys(), reverse=True)[0]
print(sorted(d[mx])[0])

Output
john

Explanation:

  • for k, v in c.items(): d[v].append(k): Maps each vote count to candidate names.
  • mx = sorted(d.keys(), reverse=True)[0]; print(sorted(d[mx])[0]): Picks the highest count, sorts tied names lexicographically.

Using max() with Custom Key

This method uses the max() function with a custom key to quickly find the candidate having the most votes while resolving ties by choosing the lexicographically smaller name.

Python
votes = ['john','johnny','jackie','johnny','john','jackie','jamie','jamie','john','johnny','jamie','johnny','john']
d = {}

for i in votes:
    d[i] = d.get(i, 0) + 1
print(max(sorted(d), key=lambda x: d[x]))

Output
john

Explanation:

  • d[i] = d.get(i, 0) + 1: Counts votes for each candidate.
  • max(sorted(d), key=lambda x: d[x]): Finds candidate with most votes; sorted() ensures lexicographically smaller name on tie.

Article Tags :

Explore