Dictionaries

Work through the problem before opening the solution.


add_peak

We are running an experiment about how many people are in different parts of the city each day. We have a peaks dict with cities as keys. Each city has cell phone hotspots with names like 'a23'. We want to keep track of the peak (max) number of phones seen by each spot during the day.

We get reports in real time like city='palo alto', spot='a23', and count=17, meaning there are 17 phones at that spot right now. We want to maintain a peaks dict, as shown below, that keeps track of the peak (max) number of phones seen by each spot.

peaks = {
    'palo alto': {'a23': 9, 'hf7': 14, 'q': 214},
    'san diego': {'p2': 22, 'v7': 1},
    ...
}

Write code for an add_peak() function which takes in a peaks dict (possibly empty), a city, a spot name, and the current number of phones at that spot, and adds that data to the peaks data if needed. In all cases, return the peaks dict. Only replace the count for an existing spot if the new count is larger.

>>> add_peak({'palo alto': {'a23': 4}}, 'palo alto', 'z15', 9)
{'palo alto': {'a23': 4, 'z15': 9}}
>>> add_peak({'palo alto': {'a23': 4, 'z15': 9}},
...          'palo alto', 'z15', 12)
{'palo alto': {'a23': 4, 'z15': 12}}

def add_peak(peaks, city, spot, count):
View solution
def add_peak(peaks, city, spot, count):
    if city not in peaks:
        peaks[city] = {}

    spots = peaks[city]
    if spot not in spots:
        spots[spot] = count
    elif spots[spot] < count:
        spots[spot] = count

    return peaks