Dictionary and Counter in Python to Find Winner Of Election (original) (raw)

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:

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:

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]))

`