Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Counting with a Dictionary
Counting how often each value appears is one of the most useful things you can do with a dictionary, and you will do it constantly once you reach data work.
The pattern:
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1Read that middle line carefully. counts.get(item, 0) says "how many have I seen so far, or 0 if this is the first". Then you add 1 and store it back. Without the .get default, the very first time you see a value you would get a KeyError.
Iterating a dictionary:
for key in counts: # just the keys for key, value in counts.items(): # both at once
Your task:
Write count_labels(labels) that takes a list of labels and returns a dictionary mapping each label to how many times it appeared.
["cat", "dog", "cat"] returns {"cat": 2, "dog": 1}.
Example Tests
Repeated labels are counted, not overwritten
Input: {"labels":["cat","dog","cat"]}
Expected: {"cat":2,"dog":1}
Every label appearing once gives every count as 1
Input: {"labels":["a","b","c"]}
Expected: {"a":1,"b":1,"c":1}
One label repeated is counted correctly
Input: {"labels":["spam","spam","spam","spam"]}
Expected: {"spam":4}
def count_labels(labels):
"""
Count how many times each label appears.
Args:
labels: a list of strings
Returns:
A dict mapping label -> count.
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests