The dictionary: a key and a value
Section 10: Dictionaries (dict)Lesson 10.1 · ⏱ 9 min
A list keeps things in order and we reach them by a number. But a dictionary keeps every value under a name (a key), like a phone book: we look up the name and find the number.
- We write it between curly brackets
{ }:"Ali": 11means the key Ali and its value 11. ages["Mona"]gives us Mona's value.ages["Sara"] = 9adds a new key, and with a key that exists it changes its value."Omar" in agesasks: is the key there?
ages = {"Ali": 11, "Mona": 12, "Omar": 10}
print(ages["Mona"])
ages["Sara"] = 9
ages["Ali"] = 12
print(ages)
for name in ages:
print(name, "is", ages[name])
print("Omar" in ages)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗12
{'Ali': 12, 'Mona': 12, 'Omar': 10, 'Sara': 9}
Ali is 12
Mona is 12
Omar is 10
Sara is 9
True
📌 Another example: counting words
The dictionary counts how many times each word appears.
text = "red blue red green blue red"
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1
print(counts)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗{'red': 3, 'blue': 2, 'green': 1}✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
Test yourself
- Make a dictionary of three of your friends and their favourite colours, and print each one's colour on a line.
🎯 Challenge yourself
Easy
A dictionary of three capitals, and print the capital of Egypt.
👀 Show the solution🙈 Hide the solution
capitals = {"Egypt": "Cairo", "France": "Paris", "Japan": "Tokyo"}
print(capitals["Egypt"])
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Cairo
Result: Cairo
Medium
Change a value, add a key, and delete a key (del).
👀 Show the solution🙈 Hide the solution
stock = {"pens": 10, "books": 4}
stock["pens"] = 12
stock["bags"] = 3
del stock["books"]
print(stock)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗{'pens': 12, 'bags': 3}Result: {'pens': 12, 'bags': 3}
Hard
Count how many times each letter appears in a word.
👀 Show the solution🙈 Hide the solution
word = "banana"
counts = {}
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗{'b': 1, 'a': 3, 'n': 2}Result: {'b': 1, 'a': 3, 'n': 2}

