Dictionaries and Sets in Python
Explore dict and set construction, membership testing, and common patterns like counting frequencies with collections.Counter.
Dictionaries and Sets in Python is a free DSA Interview Prep lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DSA Interview Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)defaultdict for Cleaner Grouping
defaultdict(list) auto-creates an empty list for any new key, so grouping problems lose their boilerplate. defaultdict(int) starts every key at 0 for easy counting.
from collections import defaultdict
groups = defaultdict(list)
words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
for w in words:
key = ''.join(sorted(w)) # canonical anagram key
groups[key].append(w)
print(list(groups.values()))
# [['eat','tea','ate'], ['tan','nat'], ['bat']]Counter: Fast Frequency Maps
Counter is a dict built for counting: hand it any iterable and get a frequency map instantly. most_common(k) returns the top k. The code shows an anagram check.
from collections import Counter
c = Counter('abracadabra')
print(c) # Counter({'a':5,'b':2,'r':2,'c':1,'d':1})
print(c.most_common(2)) # [('a', 5), ('b', 2)]
# Valid anagram check
def is_anagram(s, t):
return Counter(s) == Counter(t)
print(is_anagram('anagram', 'nagaram')) # TruePython Sets: Unordered Unique Collections
A set holds unique items with O(1) membership tests. Use {1, 2, 3} or set(iterable) — but {} makes a dict, so use set() for an empty one. Great for spotting duplicates.
seen = set()
nums = [1, 2, 3, 2, 1, 4]
duplicates = []
for n in nums:
if n in seen: # O(1) check
duplicates.append(n)
seen.add(n)
print(duplicates) # [2, 1]
print(len(seen)) # 4 (unique values)Set Operations for Interviews
Sets do math: | union, & intersection, - difference, ^ symmetric difference. These solve "common elements" style questions in one line.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # {1, 2, 3, 4, 5, 6} union
print(a & b) # {3, 4} intersection
print(a - b) # {1, 2} difference
print(a ^ b) # {1, 2, 5, 6} symmetric diffMembership Testing: List vs Set
The structure you pick changes speed. Checking in on a list is O(n); on a set it is O(1). Converting a list to a set before repeated lookups is a common speedup.
word_list = ['apple', 'banana', 'cherry', 'date']
word_set = set(word_list)
# O(n) per check
print('banana' in word_list) # True
# O(1) per check
print('banana' in word_set) # True
# Practical example: find common elements
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7]
common = [x for x in a if x in set(b)]
print(common) # [3, 4, 5]Iterating Dicts: Keys, Values, Items
Loop a dict with .keys(), .values(), or .items(). Never delete keys mid-loop — collect them in a list first, then delete after. See the code.
scores = {'Alice': 90, 'Bob': 75, 'Carol': 88}
for name, score in scores.items():
print(f'{name}: {score}')
# Find key with max value
best = max(scores, key=scores.get)
print(best) # Alice
# Safe deletion
to_del = [k for k, v in scores.items() if v < 80]
for k in to_del:
del scores[k]
print(scores) # {'Alice': 90, 'Carol': 88}Frozenset: Hashable Sets
A frozenset is an immutable set, so it can be a dict key or live inside another set. Handy for grouping anagrams by their letter set when order does not matter.
from collections import defaultdict
words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
groups = defaultdict(list)
for w in words:
key = frozenset(w) # hashable; 'eat','tea','ate' all share same key
groups[key].append(w)
print([sorted(g) for g in groups.values()])
# [['ate','eat','tea'], ['nat','tan'], ['bat']]Dict Comprehensions for Transformations
Dict comprehensions build a mapping in one line: {k: v for ...}. Great for inverting a dict or filtering pairs. Note: inverting assumes values are unique. See the code.
# Invert a dict
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1:'a', 2:'b', 3:'c'}
# Filter by value
scores = {'Alice': 90, 'Bob': 55, 'Carol': 78}
passing = {k: v for k, v in scores.items() if v >= 60}
print(passing) # {'Alice': 90, 'Carol': 78}Longest Consecutive Sequence
Sets crack longest consecutive sequence in O(n): drop all numbers in a set, then count up only from each number whose predecessor is missing. No sorting needed.
def longest_consecutive(nums):
num_set = set(nums)
best = 0
for n in num_set:
if n - 1 not in num_set: # start of sequence
cur = n
streak = 1
while cur + 1 in num_set:
cur += 1
streak += 1
best = max(best, streak)
return best
print(longest_consecutive([100,4,200,1,3,2])) # 4 (1,2,3,4)Quick Check
Quick check — see how well the dict and set ideas from this lesson stuck. Trust your instincts here. 🎯
Lesson Recap
Recap: dicts give O(1) lookups for counting and grouping, Counter and defaultdict cut the boilerplate, and sets turn O(n) scans into O(1) checks.
Frequently asked questions
Is the “Dictionaries and Sets in Python” lesson free?
Yes — the full text of “Dictionaries and Sets in Python” is free to read here on the web, and the DSA Interview Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DSA Interview Prep course, upgrade to CoddyKit PRO.
What will I learn in “Dictionaries and Sets in Python”?
Explore dict and set construction, membership testing, and common patterns like counting frequencies with collections.Counter. You practise DSA Interview Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start DSA Interview Prep?
No prior experience is required. DSA Interview Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Dictionaries and Sets in Python” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this DSA Interview Prep lesson?
Yes. Every DSA Interview Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Lists, Tuples, and Slicing
- Dictionaries and Sets in Python
- Comprehensions and Built-ins
- Functions, Closures, and Lambda