📘 Lesson 13 · Intermediate

Python Dictionaries

Master Python dicts — create, access, update, iterate with get(), items(), keys() and examples.

What is a Dictionary?

A dictionary stores data as key-value pairs, like a real dictionary where you look up a word (key) to get its definition (value). Keys must be unique and immutable (strings or numbers). Values can be anything. Dictionaries are defined with curly braces and maintain insertion order in Python 3.7+.

create.py
person = {{
    "name": "Alice",
    "age": 28,
    "city": "London"
}}
print(person["name"])              # direct access
print(person.get("age"))          # safe access
print(person.get("email", "N/A")) # default if key missing
▶ Output
Alice
28
N/A

Always prefer .get(key, default) over direct bracket access when a key might not exist. Direct access raises a KeyError if the key is missing; .get() returns None or your specified default instead — no crash.

Modifying Dictionaries

modify.py
d = {{"a": 1, "b": 2}}
d["c"] = 3         # add new key
d["a"] = 10        # update existing value
print(d)
del d["b"]          # delete key (raises KeyError if missing)
val = d.pop("a")   # remove and return the value
print(f"Removed: {val} | Left: {d}")
▶ Output
{{'a': 10, 'b': 2, 'c': 3}}
Removed: 10 | Left: {{'c': 3}}

Iterating

Use .items() to loop over both keys and values at once. Use .keys() for just keys, .values() for just values. This is the standard way to process all entries in a dictionary.

iterate.py
scores = {{"Alice": 95, "Bob": 82, "Eve": 91}}

for name, score in scores.items():
    grade = "A" if score >= 90 else "B"
    print(f"  {name}: {score} ({grade})")

print("Top scorer:", max(scores, key=scores.get))
▶ Output
  Alice: 95 (A)
  Bob: 82 (B)
  Eve: 91 (A)
Top scorer: Alice
Dictionary comprehensions let you build dicts concisely: {{k: v*2 for k, v in d.items()}} doubles every value.

🧠 Quick Check

Which method safely returns a default when a key is missing?

fetch()
find()
get()
lookup()

Tags

dictionarydictkeysvaluesitemsgetupdatenested dict