انتقل للمحتوى
Robo EgyptRobo Egypt
☰ Course contents
Robo Python: home
0. Lab tour1
1. The start5
2. Variables and input5
3. Conditions5
4. Loops5
5. Lists4
6. Functions4
7. Drawing with the turtle3
8. The project: the guess-the-number game3
9. Strings in depth1
10. Dictionaries (dict)3
11. Randomness and errors3
12. Classes and objects (class)2
13. Pro drawing and charts3
14. The final project: the quiz game2

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": 11 means the key Ali and its value 11.
  • ages["Mona"] gives us Mona's value.
  • ages["Sara"] = 9 adds a new key, and with a key that exists it changes its value.
  • "Omar" in ages asks: 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:
12
{'Ali': 12, 'Mona': 12, 'Omar': 10, 'Sara': 9}
Ali is 12
Mona is 12
Omar is 10
Sara is 9
True
🐍 Open the code in Robo Python ↗
The dictionary in Robo Python
The dictionary in Robo Python

📌 Another example: counting words

The dictionary counts how many times each word appears.

🐍 Counting words
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:
{'red': 3, 'blue': 2, 'green': 1}
🐍 Open the code in Robo Python ↗
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lessonor open the lab in a new page ↗

Test yourself

1. d = {"a": 1} then d["a"] = 5 . What is d["a"] now?
  1. 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
🐍 Solution
capitals = {"Egypt": "Cairo", "France": "Paris", "Japan": "Tokyo"}
print(capitals["Egypt"])
🖥️ The output in Robo Python:
Cairo
🐍 Open the code in Robo Python ↗

Result: Cairo

Medium

Change a value, add a key, and delete a key (del).

👀 Show the solution
🐍 Solution
stock = {"pens": 10, "books": 4}
stock["pens"] = 12
stock["bags"] = 3
del stock["books"]
print(stock)
🖥️ The output in Robo Python:
{'pens': 12, 'bags': 3}
🐍 Open the code in Robo Python ↗

Result: {'pens': 12, 'bags': 3}

Hard

Count how many times each letter appears in a word.

👀 Show the solution
🐍 Solution
word = "banana"
counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)
🖥️ The output in Robo Python:
{'b': 1, 'a': 3, 'n': 2}
🐍 Open the code in Robo Python ↗

Result: {'b': 1, 'a': 3, 'n': 2}

Finished the lesson? Mark it so your progress counts.