Python Dictionaries
EasyA Python dictionary is a mutable collection of key-value pairs with O(1) average lookup time.
Why It Matters
Dictionaries are essential for fast lookups, counting, grouping, and caching. Most coding interviews test dictionary manipulation.
How It Works
Created with {} or dict(). Keys must be immutable (str, int, tuple of immutables). Values can be anything. Access: d[key] raises KeyError if missing; d.get(key, default) returns default instead. d.setdefault(key, val) returns existing value or sets and returns val. d.update(other_dict) merges. Iteration: d.keys(), d.values(), d.items(). Since Python 3.7, dictionaries maintain insertion order.
Example
scores = {'Alice': 85, 'Bob': 92}
scores['Charlie'] = 78
scores.get('Dave', 0) # returns 0, no KeyError
Code Example
# Counting pattern
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
count = Counter(words) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# Manual counting
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
Common Mistakes
Using d[key] on a potentially missing key without get() or a try/except. Using mutable types (lists, dicts) as dictionary keys — they're unhashable and raise TypeError.
Ad Space
Test Your Understanding
Easy
Q1
What is the output? d = {'a': 1, 'b': 2} print(d.get('c', 0))
Easy
Q2
Which of the following can be a dictionary key in Python?
Easy
Q3
What is the output? d = {} d[[1,2]] = 'hello' print(d)
Ready to Master Python Dictionaries?
Practice with adaptive questions. Track your misconceptions. Build real mastery.
Sign Up Free & Start PracticingFree account. No credit card required.
Ad Space