Python · Module 04: Built-In Data StructuresTutorial 11 of 30

4.3 Dictionaries (Hash Maps), .get(), defaultdict & Counter

Master Python's fastest lookup structure: how dictionaries achieve O(1) speed with hashing, safe lookups with .get(), merging dicts with |, and counting frequencies in 1 line with Counter.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What Is a Dictionary? (The Phonebook / Locker-Tag Analogy)

In a list, you look up items by numeric position (items[0], items[1]). In a dictionary (dict), you look up values by a meaningful key (prices["milk"], user["email"]) — just like looking up a friend's phone number by their name!

Under the hood, a Python dict is a Hash Table: it runs a fast math function hash(key) to jump straight to the exact bucket in O(1) instant time — whether the dictionary has 5 items or 5 million items!

Visual: Why `prices["milk"]` Finds Values in 1 Step — Even With 1,000,000 Keys!
Immutable Key"milk"→hash("milk")% table_size = 2→[0]"tea" : $4[1](empty)[2]"milk" : $3 ✓[3]"eggs" : $6

(Since Python 3.7+, dictionaries also remember the exact insertion order of your keys!)


2. Creating, Reading & Updating Safely (.get() Prevents KeyError)

PYTHON
user = {
    "name": "Aarav",
    "role": "Backend Dev",
    "age": 24,
}

# 1) Direct lookup (crashes with KeyError if key is missing!)
print(user["name"])               # Aarav

# 2) Safe lookup with .get(key, default) — NEVER crashes!
print(user.get("city", "Unknown")) # Unknown

# 3) Add or update a key
user["city"] = "Bengaluru"
user["age"] = 25

# 4) Remove a key cleanly
removed_role = user.pop("role", None)

Merging Two Dictionaries (Modern Python 3.9+)

PYTHON
defaults = {"theme": "light", "font_size": 14}
custom   = {"theme": "dark"}

config = defaults | custom   # Right side wins on duplicate keys!
print(config)                # {'theme': 'dark', 'font_size': 14}

3. Looping Over a Dictionary Cleanly

Always use .items() when you need both the key and the value:

PYTHON
scores = {"Aarav": 92, "Riya": 97, "Kabir": 85}

for name, score in scores.items():
    print(f"{name} -> {score}")

# Just keys:   for name in scores:
# Just values: for score in scores.values():

4. Two Built-In Superpowers: Counter & defaultdict

Stop writing clunky if key not in counts: boilerplate! Python's collections module gives you two pro tools:

PYTHON
from collections import Counter, defaultdict

# 1) Count frequencies of anything in ONE line!
words = ["apple", "banana", "apple", "mango", "apple", "banana"]
freq = Counter(words)
print(freq)                  # Counter({'apple': 3, 'banana': 2, 'mango': 1})
print(freq.most_common(2))   # [('apple', 3), ('banana', 2)]

# 2) Group items automatically without KeyError!
groups = defaultdict(list)
for word in ["cat", "car", "dog", "deer"]:
    groups[word[0]].append(word)
print(dict(groups))          # {'c': ['cat', 'car'], 'd': ['dog', 'deer']}

5. Interactive Trace: Counting Character Frequencies with .get()

Watch how .get(ch, 0) + 1 builds a frequency map in a single pass:

Tracing Word Frequency Counting with a Dictionary
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→counts = {}
2for ch in "aba":
3 counts[ch] = counts.get(ch, 0) + 1
4print(counts)
Variables in Memory
counts{}dict
Console Output
(nothing printed yet)
What just happened: Start with an empty dictionary {}.

Quick Quiz: Module 4.3 — Dictionaries

Q1.Given `d = {"a": 1}`, what does `d.get("z", 0)` return?
Q2.How fast is checking `if key in my_dict:` on average?
Q3.Which of these is NOT allowed as a dictionary key?

Keep Exploring: Related Lessons & Tools

All Courses →