Data structures and algorithms · Lesson 18 of 60 · Code lesson, JavaScript or Python · Optional
Maps and dictionaries
A map (a dictionary in Python, an object in JavaScript) stores values under keys, so you can look one up by name.
Looking up a key is fast, even when the map holds many items.
Counting is a classic use: each word is a key and its count is the value.
Worked example
In JavaScript, counts[word] reads a key, and (counts[word] || 0) gives 0 when the key is missing.
const ages = { Ada: 12, Mia: 9 };
console.log(ages["Mia"]);Output: 9
In Python, counts.get(word, 0) gives 0 when the key is missing.
ages = {"Ada": 12, "Mia": 9}
print(ages["Mia"])Output: 9
Your turn
The program should count how many times each word appears, then print the count for apple. Right now every count stays at 1. Fix the counting.
Your program is checked with these 3 inputs:
Input:
apple pear apple
Expected output:
2
Input:
pear pear
Expected output:
0
Input:
apple apple apple apple
Expected output:
4
Loading your practice…
Preparing your workspace…