Dictionary and Counter in Python to Find Winner Of Election
Last Updated :
13 Nov, 2025
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])
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])
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]))
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.
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice