Courses/Python Mastery/Module 5: Data Structures
Module 5 · Lesson 330 minBeginner

Dictionaries: The Key-Value Superpower

Lesson goal
Map keys to values and unlock the data structure every real API uses.

Dictionaries: The Key-Value Superpower

Lists find things by position. Dictionaries find things by name. This single difference makes dictionaries the most important data structure in programming — every API response, every config file, every JSON on the internet is dictionary-shaped.

The mental model: a real dictionary

A paper dictionary maps words → meanings. You don't look up "the 347th word" — you jump straight to the word. Python dictionaries work identically:

code
student = {
    "name": "Aarav",
    "age": 16,
    "grade": "10th",
    "is_topper": True
}

print(student["name"])     # Aarav — jump straight to it
print(student["age"])      # 16

Curly braces, key: value pairs, commas between. Read a value by its key, never by position.

The four essential moves

code
student = {"name": "Aarav", "age": 16}

# 1. Read
print(student["name"])

# 2. Add (just assign a new key)
student["grade"] = "10th"

# 3. Update (same syntax as add — key exists? update. Missing? create.)
student["age"] = 17

# 4. Delete
del student["grade"]
print(student)        # {'name': 'Aarav', 'age': 17}

Add and update share one syntax — Python decides based on whether the key already exists.

The safe reads: .get() and .keys()

Direct access crashes on missing keys:

code
print(student["email"])      # KeyError: 'email' 💥

.get() returns a default instead:

code
print(student.get("email"))            # None — no crash
print(student.get("email", "N/A"))     # "N/A" — your chosen default

Loop over what exists:

code
for key in student.keys():
    print(key)

# or both at once — the most useful dict loop:
for key, value in student.items():
    print(f"{key}: {value}")

Output:

code
name: Aarav
age: 17

.items() hands you key AND value together — you'll use this loop constantly.

The in check

code
if "email" in student:
    print(student["email"])
else:
    print("No email on file")

in checks keys in dicts. This guard pattern prevents KeyErrors everywhere.

Why dictionaries rule the real world

Every API you'll ever call returns dictionary-shaped data:

code
weather = {
    "city": "Delhi",
    "temp": 34.5,
    "condition": "Sunny",
    "forecast": {"monday": 33, "tuesday": 35}     # dicts inside dicts!
}

print(weather["forecast"]["tuesday"])    # 35 — chain the keys

That nested access — weather["forecast"]["tuesday"] — is the single most-used line in every API project you'll build in this course.

Dicts vs lists — when to use which

QuestionContainer
Ordered collection of similar things?List — ["apple", "banana"]
Labeled properties of one thing?Dict — {"name": ..., "age": ...}
Many things, each with labels?List OF dicts — [{"name": ...}, {"name": ...}]

That last one — a list of dictionaries — is *the* shape of real-world data. You'll meet it formally next lesson.

Common Errors & Fixes

  • `KeyError: 'x'` — the key doesn't exist. Use .get() or check if "x" in dict.
  • `TypeError: unhashable type: 'list'` — you tried a list as a KEY. Keys must be immutable: strings, numbers, tuples.
  • `SyntaxError` on unquoted key accessstudent[name] looks up the *value* of a variable called name; you probably meant student["name"].

  • ✅ Checkpoint

  • How do you add a new key "city": "Delhi" to an existing dict? *(student["city"] = "Delhi")*
  • student["email"] crashes. What are two safe alternatives? *(student.get("email") or if "email" in student)*
  • What does .items() give you in a loop? *(Key and value together)*
  • Access city inside data["address"]["city"]? *(Exactly that — chain the keys)*
  • Next: nesting — combining lists and dicts into the real-world data shapes.