Goal

You’ll be able to use dictionaries and sets correctly, and understand the fundamental structural difference between a dictionary (key-value pairs) and a list (ordered sequence) that determines which one genuinely fits a given problem.

Learn

A dictionary stores data as key-value pairs, letting you look up a value by a meaningful name instead of a numeric position:

person = {"name": "Ahmed", "age": 25, "city": "Cairo"}
person["name"]     # "Ahmed"
person["age"] = 26  # update a value
person["email"] = "ahmed@example.com"  # add a new key

This is fundamentally different from a list: a list is accessed by numeric position (fruits[0]), while a dictionary is accessed by a meaningful key (person["name"]) — the right choice depends entirely on whether your data is naturally a labeled collection of attributes (dictionary) or an ordered sequence of similar items (list).

A set stores unique values only, with no meaningful order and no duplicate values allowed:

unique_ids = {1, 2, 3, 2, 1}
print(unique_ids)  # {1, 2, 3} — duplicates automatically removed

Sets are genuinely useful specifically for removing duplicates from a collection, and for fast membership testing (x in my_set is significantly faster than x in my_list for large collections).

Trying to access a dictionary key that doesn’t exist raises a KeyError. The safer approach, when a key might not exist, is .get(), which returns None (or a specified default) instead of crashing:

person.get("phone")           # None — key doesn't exist, no crash
person.get("phone", "N/A")    # "N/A" — a custom fallback default

Decision Task

You’re modeling a single user’s profile: name, email, age, and a list of their order IDs. Before reading on: would the overall profile structure be a dictionary or a list, and why specifically?

Show Answer

A dictionary — the profile has genuinely different, meaningfully-named attributes (name, email, age), not a sequence of similar interchangeable items, which is exactly what a dictionary’s key-value structure represents. The order IDs specifically, being a genuine sequence of similar items, would themselves be a list, nested as one of the dictionary’s values: {"name": ..., "order_ids": [101, 102, 103]}.

Common Mistake

Accessing a dictionary key directly with square brackets (person["phone"]) when that key might not actually exist, causing a KeyError that crashes the program. Using .get() instead, with an appropriate default value, handles the “key might not exist” case safely without crashing, whenever that’s a genuine possibility rather than a guaranteed programming error.

Practice Questions

1. Write a dictionary representing a book with keys for title, author, and year.

Show Answer

book = {"title": "Some Title", "author": "Some Author", "year": 2020}

2. Given the book dictionary above, write code that safely gets a “publisher” value that might not exist, defaulting to “Unknown” if missing.

Show Answer

book.get("publisher", "Unknown")

3. What happens if you write ids = {5, 3, 5, 1, 3}? What does ids actually contain?

Show Answer

{1, 3, 5} (order may vary since sets are unordered) — duplicates are automatically removed, since sets only store unique values.

4. True or False: dictionaries are accessed by numeric position, the same way lists are.

Show Answer

False — dictionaries are accessed by meaningful keys, not numeric position; lists use numeric position.

5. Why might a set be a better choice than a list for checking whether a specific ID has already been processed, in a program handling a large number of IDs?

Show Answer

Membership testing (checking if a value exists) is significantly faster in a set than in a list for large collections, since sets are optimized for this kind of fast lookup.

Try It Yourself

Without looking back, write a dictionary representing a simple product (name, price, in_stock), then write code that safely updates the price to a new value.

Show Answer

product = {"name": "Mouse", "price": 15.99, "in_stock": True}\nproduct["price"] = 12.99 — dictionary values can be updated directly by key assignment, since dictionaries (like lists) are mutable.

Quick Check

1. How is a dictionary accessed: by numeric position or by key?

Show Answer

By key.

2. What happens if you access a dictionary key that doesn’t exist using square brackets?

Show Answer

A KeyError is raised, crashing the program if not handled.

3. What method safely accesses a dictionary key that might not exist, without crashing?

Show Answer

.get(), optionally with a default value.

4. What’s the key characteristic of a set that distinguishes it from a list?

Show Answer

A set only stores unique values, with no duplicates and no meaningful order.

5. When might you choose a dictionary over a list for structuring data?

Show Answer

When the data has genuinely different, meaningfully-named attributes rather than a sequence of similar interchangeable items.

تحميل هذا الباب / Download this Chapterنسخة كاملة للدراسة بدون إنترنت، مع الأسئلة والإجابات والصور المتاحة.