Start learning free

LESSON 135 OF 673 · DICTIONARIES - CHALLENGES

Count a Vote in Python: Dictionary Counter with get

Practice Read the full explanation

You get votes, a dict from names to how many votes each person has. You also get the name on a new vote.

Count the new vote and return votes.

The person called name gets one more vote. A name with no votes yet isn't in votes. It starts from 0, so after this vote it has 1. The order of the entries doesn't matter.

 

Example 1:

Input: votes = {"Ana": 3, "Ben": 5}, name = "Ana"
Output: {"Ana": 4, "Ben": 5}
Explanation: Ana had 3 votes. Now she has 3 + 1 = 4.

Example 2:

Input: votes = {"Ana": 3, "Ben": 5}, name = "Cara"
Output: {"Ana": 3, "Ben": 5, "Cara": 1}
Explanation: Cara had no votes yet. She starts from 0 and now has 1.

Example 3:

Input: votes = {}, name = "Max"
Output: {"Max": 1}
Explanation: This is the very first vote. Max now has 1.

 

Constraints:

  • votes can be empty.
  • Every count in votes is at least 1.
  • Names are single words made of English letters.
STEP 1 OF 3
    Ctrl + Enter to check

    PYTHON · DICTIONARIES - CHALLENGES

    Count A Vote in Python, explained

    Problem overview

    The method countVote gets votes, a dictionary from names to how many votes each person has, and the name on a new vote. It counts the new vote and returns votes. The person called name gets one more vote. A name with no votes yet isn't in the dictionary: it starts from 0, so after this vote it has 1. The dictionary may be empty, and the order of the entries doesn't matter.

    Examples:

    • {"Ana": 3, "Ben": 5} with "Ana" gives {"Ana": 4, "Ben": 5}.
    • The same dictionary with "Cara" gives {"Ana": 3, "Ben": 5, "Cara": 1}, since she starts from 0.
    • {} with "Max" gives {"Max": 1}.

    Approach: read with a default, add one, store

    There are two cases, a known name and a new one, but they follow the same steps if the new name is treated as having 0 votes. votes.get(name, 0) gives the current count for a known name and 0 for a new one, without an error. Add 1 to that and store the result under name. For a known name, the store replaces the old count. For a new name, it adds the key.

    Reading with votes[name] would fail for a new name with a KeyError, and that is exactly the case the default avoids.

    Step by step

    1. Read the current count into count with votes.get(name, 0).
    2. Store count + 1 under the key name: votes[name] = count + 1.
    3. Return votes. Only the count of name changed, and every other entry is as it was.

    The solution in Python

    class Solution:
        def countVote(self, votes: Dict[str, int], name: str) -> Dict[str, int]:
            count = votes.get(name, 0)
            votes[name] = count + 1
            return votes
    

    On the three examples it returns:

    {'Ana': 4, 'Ben': 5}
    {'Ana': 3, 'Ben': 5, 'Cara': 1}
    {'Max': 1}
    

    The two lines of the body can be written as one, votes[name] = votes.get(name, 0) + 1, which does the same thing. Splitting them gives the old count a name. The dictionary passed in is changed in place and returned.

    Edge cases and common mistakes

    • Using brackets to read. votes[name] += 1 works for Ana but raises KeyError: 'Cara' for a name that has no votes yet.
    • Using get without a default. votes.get(name) gives None for a new name, and None + 1 fails with a TypeError.
    • Storing 1 for everyone. Writing votes[name] = 1 would reset Ana's 3 votes to 1.
    • Forgetting to store. Computing count + 1 and not assigning it leaves the dictionary unchanged.

    Another way: a counting dictionary

    Python's standard library has defaultdict, which gives 0 automatically for a missing key when created with int. It is handy in programs that count a lot, but the lesson passes a plain dictionary, so get is the tool here.

    from collections import defaultdict
    dd = defaultdict(int)
    dd["Max"] += 1
    print(dict(dd))
    
    {'Max': 1}
    

    Testing

    Call the method three times in a row on an empty dictionary with the name "Max". The results are {'Max': 1}, {'Max': 2} and {'Max': 3}: the first vote creates the entry with 1, and each later one raises it by one. A vote for another name afterwards, such as "Zoe", gives {'Max': 3, 'Zoe': 1}, and Max's count is untouched.

    Because the same dictionary is changed and returned each time, the three results above come from one dictionary growing, not from three separate ones. Copy the dictionary first (with dict(votes)) if you want to keep an earlier state.

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free