Home / Topic Library / Python / Dictionaries
🐍 Python Topic Library

Python Dictionaries — Key-Value Data Done Right

A dictionary maps keys to values — like a real dictionary maps words to definitions. It's the data structure behind JSON, API responses, and most real-world Python.

⚡ Quick Answer

Create with braces: player = {"name": "Ada", "level": 3}. Read with player["name"] or safely with player.get("coins", 0). Loop pairs with for k, v in player.items():.

§Creating & reading

basics.py
player = {"name": "Ada", "level": 3, "alive": True}

print(player["name"])          # Ada
# print(player["coins"])       # KeyError! key doesn't exist
print(player.get("coins"))     # None — safe
print(player.get("coins", 0))  # 0 — safe with default

§Adding, updating, deleting

modify.py
player = {"name": "Ada", "level": 3}
player["coins"] = 100        # add new key
player["level"] += 1         # update existing
player.update({"hp": 50, "mp": 30})   # add/update many

del player["mp"]             # delete a key
coins = player.pop("coins")  # delete AND get the value

§Looping over dictionaries

looping.py
scores = {"ada": 95, "alan": 88, "grace": 92}

for name in scores:                  # keys by default
    print(name)

for name, score in scores.items():   # keys AND values
    print(f"{name}: {score}")

best = max(scores, key=scores.get)   # key with highest value
print(best)                          # ada

§Nesting — dictionaries inside dictionaries

Real data nests. JSON from any API becomes exactly this shape in Python.

nested.py
users = {
    "ada":  {"age": 12, "langs": ["python", "scratch"]},
    "alan": {"age": 14, "langs": ["python"]},
}
print(users["ada"]["age"])          # 12
print(users["ada"]["langs"][0])     # python

for name, info in users.items():
    print(f"{name} knows {len(info['langs'])} language(s)")

§Dict comprehensions & counting

comprehension.py
squares = {n: n * n for n in range(1, 6)}
print(squares)          # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# the classic counting pattern:
text = "abracadabra"
counts = {}
for ch in text:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)           # {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}

§Common Mistakes to Avoid

🚨 Watch out for these
  • Reading missing keys with []d["nope"] raises KeyError — use d.get("nope", default) when the key might not exist
  • Using mutable keys — lists can't be dict keys (unhashable) — use tuples: d[(x, y)] = value
  • Modifying a dict while looping it — adding/removing keys inside for k in d: raises RuntimeError — loop over list(d) instead

§Frequently Asked Questions

What's the difference between a list and a dictionary?

A list is ordered and accessed by position (nums[0]); a dictionary is accessed by key (player["name"]). Use dicts when data has labels.

What does get() do that [] doesn't?

d.get(key, default) returns the default instead of crashing when the key is missing — [] raises KeyError.

Are Python dictionaries ordered?

Yes — since Python 3.7 dictionaries preserve insertion order officially.

Can dictionary values be any type?

Yes — values can be anything, including lists and other dictionaries. Keys must be immutable (strings, numbers, tuples).

🎓 Want to master Python properly?This reference covers one topic — the full free course takes you from zero to projects, with quizzes and a certificate.
Start the Free Python Course →

§Related Python Topics

← ListsIf / Else →