Topic 06 / 15
Dictionaries & Sets
Dictionaries — Python’s Most Important Structure
A dict maps keys to values with O(1) lookup. JSON objects, API payloads, config, Django querysets’ values — all dicts:
user = {
"name": "Digamber",
"channel": "Coding India",
"subscribers": 10500,
}
user["name"] # 'Digamber'
user["city"] = "Mohali" # add a key
user["subscribers"] += 100 # update
del user["city"] # remove
"name" in user # True — checks KEYSSafe Lookups
user["missing"] raises KeyError. Use get() when a key might not exist:
user.get("city") # None — no crash
user.get("city", "Unknown") # 'Unknown' — with a defaultsetdefault inserts a default only if the key is missing — perfect for grouping:
groups = {}
for word in ["apple", "ant", "bat", "bee"]:
groups.setdefault(word[0], []).append(word)
# {'a': ['apple', 'ant'], 'b': ['bat', 'bee']}(Or use collections.defaultdict(list) for the same pattern.)
Iterating Dicts
for key in user: # keys by default
print(key)
for key, value in user.items(): # the usual way
print(f"{key} = {value}")
list(user.keys())
list(user.values())Dicts preserve insertion order (guaranteed since Python 3.7).
Merging
defaults = {"theme": "dark", "lang": "en"}
prefs = {"lang": "hi"}
settings = defaults | prefs # {'theme': 'dark', 'lang': 'hi'}
# right side wins on conflictsSets — Unique, Unordered, Fast
tags = {"python", "django", "python"} # duplicates collapse
len(tags) # 2
"python" in tags # True — O(1), much faster than a list
tags.add("react")
tags.discard("django")The classic one-liner — dedupe a list:
unique = list(set([1, 2, 2, 3, 3, 3])) # [1, 2, 3] (order not guaranteed)Set Algebra
backend = {"python", "sql", "docker"}
frontend = {"javascript", "css", "docker"}
backend | frontend # union — everything
backend & frontend # intersection — {'docker'}
backend - frontend # difference — {'python', 'sql'}
backend ^ frontend # symmetric diff — in one but not bothReal use: “which users are in group A but not group B?” — one expression instead of nested loops.