Dictionaries and Sets in Python
Explore dict and set construction, membership testing, and common patterns like counting frequencies with collections.Counter.
Python Dictionaries: Key-Value Stores
A Python dict maps keys to values with O(1) average lookups, insert, and delete. It is the engine behind two-sum, anagram checks, and frequency counting. The code shows it.
d = {'apple': 3, 'banana': 5}
print(d['apple']) # 3
d['cherry'] = 7
print(len(d)) # 3
print('banana' in d) # True
del d['apple']
print(d) # {'banana': 5, 'cherry': 7}Safe Lookup with .get()
Reading a missing key with d[key] crashes with a KeyError. Use d.get(key, default) to return a fallback instead — a safe habit that avoids surprise runtime errors.
freq = {}
words = ['the', 'cat', 'sat', 'on', 'the', 'mat']
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)
# {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
print(freq.get('dog', 0)) # 0 (no KeyError)All lessons in this course
- Lists, Tuples, and Slicing
- Dictionaries and Sets in Python
- Comprehensions and Built-ins
- Functions, Closures, and Lambda