M8) Rating frequencies in a dictionary

A transportation service lets customers rate a trip in a five-star app. In this example, customers may submit any integer from 0 through 5, including a zero-star rating.

As Figure 1 shows, each submitted rating is added to a list in arrival order. The first three customers submit 0, 2, and 3, so the list begins [0, 2, 3, ...]. Repeated ratings remain separate entries.

Three customers submit ratings 0, 2, and 3 to a five-star app, which records them in the list [0, 2, 3, ...].
Figure 1: Customer ratings enter the app and form an ordered list; the first three submissions are 0, 2, and 3.

get_frequency(ratings) summarizes that list as a dictionary:

  • The keys are all six possible ratings, from 0 through 5.
  • Each value counts how often its rating appears, including a count of 0 for an unused rating.
  • An empty input list produces all six keys with counts of 0.

For the complete example [0, 2, 3, 1, 4, 2, 5, 3, 1, 2], the required result is {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, 5: 1}. For instance, rating 2 appears three times, so its dictionary entry is 2: 3.

Compare the four implementations in Listing 1.

Listing 1: Dictionary alternatives for counting customer ratings.
(a) Alternative A.
def get_frequency(ratings):
    freqs = {}
    for rating in range(1, 6):
        freqs[rating] = 0
    for rating in ratings:
        freqs[rating] += 1
    return freqs
(b) Alternative B.
def get_frequency(ratings):
    freqs = {}
    for rating in range(6):
        freqs[rating] = 0
    for index in range(len(ratings)):
        freqs[index] += 1
    return freqs
(c) Alternative C.
def get_frequency(ratings):
    freqs = {}
    for rating in range(6):
        freqs[rating] = 0
    for rating in ratings:
        freqs[rating] += rating
    return freqs
(d) Alternative D.
def get_frequency(ratings):
    freqs = {}
    for rating in range(6):
        freqs[rating] = 0
    for rating in ratings:
        freqs[rating] += 1
    return freqs

Which implementation satisfies the stated requirements?

  • range(stop) gives integers from 0 up to, excluding, stop. range(start, stop) begins at start. range(0) is empty.
  • list(values) collects the supplied values into a list. For example, list(range(3)) is [0, 1, 2], and list(range(2, 4)) is [2, 3].
  • len(ratings) returns the number of entries, including repeats: len([2, 2, 5]) is 3.