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.
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!
(Since Python 3.7+, dictionaries also remember the exact insertion order of your keys!)
2. Creating, Reading & Updating Safely (.get() Prevents KeyError)
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+)
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:
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:
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:
Quick Quiz: Module 4.3 — Dictionaries
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Compute MD5, SHA-1, SHA-256, SHA-384, and SHA-512 hashes or keyed HMAC signatures directly in your browser using Web Crypto.