Python · Module 3 · Lesson 41 min read

Dictionaries

Key → value pairs

student = {"name": "Sam", "grade": 90}

  • Lookups by key are very fast (average O(1)).
  • Keys must be unique and immutable (str, int, tuple).
  • Since Python 3.7, dicts keep insertion order.

Reading safely

  • student["age"] raises KeyError if the key is missing.
  • student.get("age") returns None instead, and student.get("age", 0) returns a default.

Updating

  • d[key] = value adds or replaces.
  • d.update(other) merges, and d | other returns a merged copy (3.9+).
  • d.pop(key) removes and returns.
  • d.setdefault(key, []) gets the value, creating it if missing.

Looping

.keys(), .values(), .items(). Most often: for key, value in d.items():

Dict comprehension

{k: v for k, v in d.items() if v >= 75}

💡 For counting, collections.Counter does the work for you.

▶️ Runs in the app.

Example

Python
student = {"name": "Sam", "grade": 90}
student["age"] = 21
print(student.get("city", "unknown"))   # unknown

for key, value in student.items():
    print(key, "->", value)

grades = {"ana": 90, "ben": 70, "cara": 82}
passed = {name: g for name, g in grades.items() if g >= 75}
print(passed)                           # {'ana': 90, 'cara': 82}

# Counting words
text = "to be or not to be"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)        # {'to': 2, 'be': 2, 'or': 1, 'not': 1}

from collections import Counter
print(Counter(text.split()).most_common(2))   # [('to', 2), ('be', 2)]