Dictionaries & Sets — O(1) Superpowers
ডিকশনারি ও সেট — Python-এর সবচেয়ে শক্তিশালী বিল্ট-ইন
1. Why Hash-Based Collections Matter
Under the hood, both dict and set are hash tables — data structures that compute a fingerprint (hash) of each key and jump to the right memory slot in a single step. This gives them average O(1) lookup, insert, and delete, no matter how many items you have. Mastering them turns O(n²) problems into O(n) solutions.
2. Dict Basics
# Creating
prices = {"rice": 70, "dal": 110, "oil": 200}
# Access
print(prices["rice"]) # 70
# Update / add
prices["rice"] = 75
prices["sugar"] = 130
# Safer access with get()
print(prices.get("tea", 0)) # 0 (default)
# Check membership
print("sugar" in prices)
# Delete
del prices["oil"]
# Iterate — items(), keys(), values()
for item, cost in prices.items():
print(f"{item}: {cost} Tk")
3. setdefault and defaultdict
Both let you avoid the "check if key exists, else create it" pattern.
from collections import defaultdict
words = ["rice", "dal", "rice", "fish", "dal", "rice"]
# Manual way
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
# Using defaultdict
counts2 = defaultdict(int)
for w in words:
counts2[w] += 1
print(dict(counts2))
# Grouping with setdefault
by_first = {}
for name in ["Asif", "Ayesha", "Akter", "Bashir"]:
by_first.setdefault(name[0], []).append(name)
print(by_first)
4. Dict Comprehension
# Build a squares table
squares = {n: n * n for n in range(1, 6)}
print(squares)
# Invert a dict (values become keys)
codes = {"BD": 880, "IN": 91, "PK": 92}
inverted = {v: k for k, v in codes.items()}
print(inverted)
# Filter a dict
prices = {"rice": 75, "dal": 110, "tea": 45}
cheap = {k: v for k, v in prices.items() if v < 100}
print(cheap)
5. Sets — Collections Without Duplicates
# Create
a = {1, 2, 3, 2, 1}
print(a) # {1, 2, 3} — duplicates removed
# Empty set — note: {} is an empty dict!
empty = set()
# Add / remove
a.add(4)
a.discard(2) # no error if missing
print(a)
# Membership is O(1)
print(3 in a)
# Set algebra
b = {3, 4, 5, 6}
print("union :", a | b)
print("intersection:", a & b)
print("difference :", a - b)
print("symmetric :", a ^ b)
# De-duplicate a list in one line
words = ["rice", "dal", "rice", "fish"]
print(set(words))
6. When to Use Which
| Use... | When you need... |
|---|---|
| list | Ordered, can have duplicates, index access |
| tuple | Immutable fixed record; hashable key |
| dict | Key → value lookup in O(1) |
| set | Fast membership testing, unique items, set algebra |
frozenset. Need a dict
that counts things? Use collections.Counter.
7. Vocabulary (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Hash table | Structure mapping keys to slots via a hash. | Hash-এর মাধ্যমে key-কে slot-এ map করা data structure। |
| Key | The lookup value in a dict. | Dict-এ lookup-এর মান। |
| Collision | Two keys hashing to the same slot. | দুটি key-এর hash একই slot-এ যাওয়া। |
| Load factor | Fraction of hash table filled. | Hash table-এ পূরণকৃত অংশ। |
| defaultdict | dict with a factory for missing keys. | missing key-এর জন্য default value-সহ dict। |
8. Practice Problems
-
Given a string, count the frequency of each character using a dict.একটি string নিয়ে প্রতিটি character কতবার এসেছে তা dict-এ রাখুন।
✨ Show Answer (উত্তর দেখুন)
ans1.pys = "programming" freq = {} for ch in s: freq[ch] = freq.get(ch, 0) + 1 print(freq) -
Find the unique words in two sentences using set operations.Set ব্যবহার করে দুটি বাক্যে unique শব্দ বের করুন।
✨ Show Answer (উত্তর দেখুন)
ans2.pys1 = "python is easy to read" s2 = "python is easy to write" w1, w2 = set(s1.split()), set(s2.split()) print("common:", w1 & w2) print("only in 1:", w1 - w2) print("only in 2:", w2 - w1) -
Build a dict of squares for 1..10 using dict comprehension.১ থেকে ১০ পর্যন্ত সংখ্যার square dict comprehension দিয়ে তৈরি করুন।
✨ Show Answer (উত্তর দেখুন)
ans3.pysquares = {n: n ** 2 for n in range(1, 11)} print(squares) -
Explain in 2 sentences why
[1, 2]cannot be a key in a dict but(1, 2)can.ব্যাখ্যা করুন:[1, 2]dict key হতে পারে না, কিন্তু(1, 2)পারে।✨ Show Answer (উত্তর দেখুন)
Answer: Dict keys must be hashable, and only immutable objects are hashable. A list is mutable, so its identity (and hash) could change while it's in use as a key — breaking the dict. A tuple of hashable items is immutable, so its hash is stable and safe.
Dict-এর key hashable হতে হয়, এবং শুধু immutable object hashable। List mutable — ব্যবহার করা অবস্থায় এর hash বদলে গিয়ে dict ভেঙে যেতে পারে। Tuple immutable, তাই এর hash স্থির ও নিরাপদ।
-
Given
names = ["Asif","Mou","Asif","Rafi","Mou"], find duplicates and unique names using sets.উপরের list থেকে set ব্যবহার করে duplicate ও unique নাম বের করুন।✨ Show Answer (উত্তর দেখুন)
ans5.pynames = ["Asif", "Mou", "Asif", "Rafi", "Mou"] seen, dupes = set(), set() for n in names: (dupes if n in seen else seen).add(n) print("unique:", seen - dupes) print("duplicates:", dupes)
Summary — Module 16
dict and set are hash-backed and give you O(1) lookups. Use dict.get(key, default)
or defaultdict instead of verbose "check then insert" patterns. Sets are perfect for uniqueness,
membership, and set algebra. Choose the right container and you will write less code that runs faster.
dict ও set — hash-ভিত্তিক, O(1) lookup। verbose "check then insert"-এর পরিবর্তে dict.get() বা defaultdict ব্যবহার করুন। Set — uniqueness, membership ও set-algebra-র জন্য আদর্শ। সঠিক container বেছে নিলে কোড ছোট ও দ্রুত হয়।