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.
get_frequency(ratings) summarizes that list as a dictionary:
- The keys are all six possible ratings, from
0through5. - Each value counts how often its rating appears, including a count of
0for 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.
Which implementation satisfies the stated requirements?
TipHint
range(stop)gives integers from0up to, excluding,stop.range(start, stop)begins atstart.range(0)is empty.list(values)collects the supplied values into a list. For example,list(range(3))is[0, 1, 2], andlist(range(2, 4))is[2, 3].len(ratings)returns the number of entries, including repeats:len([2, 2, 5])is3.