Strings & Data Structures
Dictionaries
Complete lesson for Dictionaries using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Dictionaries
Section: Strings & Data Structures. Python dictionaries — key-value maps, lookup, update, nesting, and real-life examples.
What is a dictionary?
- A **dictionary** (
dict) stores **key → value** pairs. Lookup by key is average O(1). - Keys must be **hashable** (immutable types like
str,int,tupleof immutables). Values can be any object. - Since Python 3.7+, insertion order is preserved.
- **Real-life:** a phone book (name → number), a menu (item → price), student roll → marks.
| Idea | Meaning | Example |
|---|---|---|
| Key | Unique label | 'name', 101 |
| Value | Data stored under the key | 'Ada', 95 |
| Pair | One mapping | 'city': 'Pune' |
| Empty dict | No pairs yet | {} or dict() |
student = {"name": "Ada", "age": 20, "city": "Pune"}
print(student)
print(student["name"])
print(type(student)) Differences between list, tuple, set, and dictionary
- These four are the core built-in collections. Pick by **mutability**, **order**, **duplicates**, and whether you need **key → value** lookup.
- Quick rule: **list** = ordered changeable sequence; **tuple** = ordered fixed record; **set** = unique items / fast membership; **dict** = labeled values by key.
- Empty literals:
[]list,()tuple,set()set ({}is an empty **dict**, not a set).
| Feature | list | tuple | set | dictionary |
|---|---|---|---|---|
| Literal | [1, 2] | (1, 2) | {1, 2} | {'a': 1} |
| Empty form | [] | () | set() | {} / dict() |
| Ordered? | Yes | Yes | No (do not rely on order) | Yes (insertion order, 3.7+) |
| Mutable? | Yes | No | Yes | Yes |
| Allows duplicates? | Yes | Yes | No (unique elements) | Keys unique; values may repeat |
Indexing x[i]? | Yes | Yes | No | By key: d[key] (not position) |
| Slicing? | Yes | Yes | No | No |
| Hashable / dict key? | No | Yes (if elements hashable) | No (frozenset yes) | No (keys must be hashable) |
Typical in cost | O(n) | O(n) | ≈ O(1) | ≈ O(1) on keys |
| Main methods idea | Many (append, sort, …) | Only count, index | Algebra + add/remove | get, update, keys, … |
| Best for | Growable ordered data | Fixed records / multi-return | Uniques & fast membership | Named lookup / mappings |
| Real-life example | Todo list, playlist | GPS (lat, lon), RGB | Unique tags, visitor IDs | Phone book, menu prices |
| Example | [10, 20, 10] | (10, 20) | {10, 20} | {'math': 90, 'sci': 85} |
Create dictionaries
- Literal:
{"a": 1, "b": 2}. Constructor:dict(a=1, b=2)ordict([("a", 1)]). dict.fromkeys(keys, default)builds a dict with the same starting value for every key.- Duplicate keys in a literal keep the **last** value written.
a = {"x": 1, "y": 2}
b = dict(name="Sam", score=88)
c = dict([("a", 10), ("b", 20)])
d = dict.fromkeys(["math", "sci", "eng"], 0)
print(a, b, c, d) Built-in functions that work on dictionaries
- These are **built-in functions** (not dict methods). Call them as
len(d), notd.len(). - Iterating a dict yields **keys**. Use
d.values()/d.items()when you need values or pairs.
| Function | What it does | Example | Result |
|---|---|---|---|
len(d) | Number of keys | len({"a": 1, "b": 2}) | 2 |
dict(...) | Build a dict | dict(x=1, y=2) | {"x": 1, "y": 2} |
dict.fromkeys(keys, default) | Same default for every key | dict.fromkeys(["a","b"], 0) | {"a": 0, "b": 0} |
list(d) | List of keys (insertion order) | list({"b": 1, "a": 2}) | ["b", "a"] |
sorted(d) | Sorted list of keys | sorted({"b": 1, "a": 2}) | ["a", "b"] |
sorted(d, key=d.get) | Keys sorted by value | sorted({"a": 2, "b": 1}, key=d.get) | ["b", "a"] |
reversed(d) | Keys in reverse insertion order (3.8+) | list(reversed({"a":1,"b":2})) | ["b", "a"] |
min(d) / max(d) | Min / max **key** | min({"b": 9, "a": 1}) | "a" |
sum(d.values()) | Sum values (when numeric) | sum({"a": 1, "b": 2}.values()) | 3 |
any(d) / all(d) | Truthy checks on **keys** | any({0: "x", 1: "y"}) | True |
isinstance(d, dict) | Type check | isinstance({}, dict) | True |
zip(keys, values) + dict | Build from parallel sequences | dict(zip(["a","b"], [1,2])) | {"a": 1, "b": 2} |
Access and safe get
d[key]raisesKeyErrorif missing. Preferd.get(key)/d.get(key, default).key in dchecks existence without raising.- **Real-life:** asking a receptionist for a room — get a default “not found” instead of crashing.
| API | What it does | Example | Notes |
|---|---|---|---|
d[key] | Get value | d["tea"] | Raises KeyError if missing |
d.get(key) | Safe get | d.get("juice") | Returns None if missing |
d.get(key, default) | Safe get with default | d.get("juice", 0) | Returns default if missing |
key in d | Membership on keys | "tea" in d | Does not check values |
key not in d | Missing-key test | "juice" not in d | Boolean |
prices = {"tea": 20, "coffee": 40}
print(prices["tea"])
print(prices.get("juice"))
print(prices.get("juice", 0))
print("tea" in prices)
print("juice" not in prices) dict methods — add, update, delete
- Assign:
d[key] = valueinserts or overwrites. d.update(other)merges another mapping or iterable of pairs.- Delete:
del d[key],d.pop(key),d.pop(key, default),d.clear(),d.popitem()(last inserted pair in 3.7+).
| Method / op | What it does | Example | Notes |
|---|---|---|---|
d[key] = value | Insert or overwrite | d["a"] = 1 | Most common write |
d.update(other) | Merge mapping / pairs | d.update({"b": 2}) | Later keys win |
d |= other | In-place merge (3.9+) | d |= {"c": 3} | Like update |
d | other | New merged dict (3.9+) | d | {"c": 3} | Originals unchanged |
del d[key] | Delete key | del d["a"] | Raises if missing |
d.pop(key) | Remove and return value | d.pop("a") | Raises if missing |
d.pop(key, default) | Pop with default | d.pop("z", None) | No error if missing |
d.popitem() | Remove last inserted pair | d.popitem() | Returns (key, value) |
d.clear() | Remove all pairs | d.clear() | Becomes {} |
d.setdefault(key, default) | Get or insert default | d.setdefault("a", []) | Returns value |
d.copy() | Shallow copy | e = d.copy() | Nested objects shared |
cart = {"apple": 2}
cart["banana"] = 3
cart["apple"] = 5
cart.update({"milk": 1, "banana": 4})
print(cart)
removed = cart.pop("milk")
print(removed, cart)
del cart["apple"]
print(cart) keys, values, items
d.keys(),d.values(),d.items()return dynamic views — they reflect later changes.- Loop with
for k, v in d.items():for readable pair iteration. - Convert to list when you need a snapshot:
list(d.items()).
| Method | What it does | Example | Typical use |
|---|---|---|---|
d.keys() | View of keys | list(d.keys()) | Iterate / test membership of keys |
d.values() | View of values | list(d.values()) | Aggregate values (sum, max) |
d.items() | View of (key, value) pairs | for k, v in d.items() | Most readable loop |
list(d.items()) | Snapshot list of pairs | list(d.items()) | Freeze before mutating |
marks = {"Ada": 90, "Bob": 75, "Cia": 88}
print(list(marks.keys()))
print(list(marks.values()))
for name, score in marks.items():
print(f"{name} -> {score}") setdefault and counting pattern
d.setdefault(key, default)returns existing value, or insertsdefaultand returns it.- Classic use: group lists or initialize counters without a separate
if key not in d. - For heavy counting prefer
collections.Counter; for grouping preferdefaultdict(list).
groups = {}
for word in ["hi", "hello", "hey", "hi"]:
groups.setdefault(word[0], []).append(word)
print(groups)
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts) dict APIs — overview cheat sheet
- Use this map to pick the right tool; the tables above have examples.
| Category | Common APIs | Use when |
|---|---|---|
| Built-ins | len, dict, sorted, reversed, zip + dict | Create, measure, order keys |
| Read | d[key], get, in | Lookup without crashing |
| Write / merge | d[key]=, update, |, |= | Insert or combine maps |
| Delete | del, pop, popitem, clear | Remove pairs |
| Views | keys, values, items | Iterate structure |
| Helpers | setdefault, copy, fromkeys | Initialize, group, duplicate |
Nested dictionaries
- Values can be dicts (or lists of dicts) for structured records.
- Access with chained keys:
data["user"]["email"]. Use.getcarefully at each level. - **Real-life:** JSON-like employee directory: id → {name, dept, contacts}.
company = {
"e1": {"name": "Ada", "dept": "AI", "skills": ["python", "ml"]},
"e2": {"name": "Bob", "dept": "Web", "skills": ["js", "css"]},
}
print(company["e1"]["name"])
print(company["e2"]["skills"][0])
company["e1"]["skills"].append("pandas")
print(company["e1"]) Copying and shallow pitfalls
d.copy()/dict(d)is a **shallow** copy: nested mutable values are shared.- Assignment
b = aaliases the same object; mutating through either name changes both. - Deep copy nested structures with
copy.deepcopywhen needed.
import copy
a = {"x": 1, "nums": [1, 2]}
b = a
c = a.copy()
d = copy.deepcopy(a)
b["x"] = 9
c["nums"].append(3)
d["nums"].append(99)
print("a", a)
print("c", c)
print("d", d) Advanced — Dictionaries
Hashable keys and equality
- Only hashable keys are allowed. Lists and dicts cannot be keys; frozensets and tuples of hashables can.
- Equal keys collide:
1and1.0andTruecan act as the same key in edge cases because they compare equal and hash equal. - Custom objects need stable
__hash__and__eq__if used as keys.
ok = {(1, 2): "point", frozenset({1, 2}): "set-key"}
print(ok[(1, 2)])
d = {}
d[1] = "int"
d[True] = "bool-overwrites-1"
d[1.0] = "float-same-bucket"
print(d) Merging dicts (3.9+ and unpacking)
d | otherreturns a new merged dict;d |= otherupdates in place (3.9+).{**a, **b}unpacks; later keys win on conflict.updatemutates;|keeps originals unless you assign back.
a = {"x": 1, "y": 2}
b = {"y": 9, "z": 3}
print(a | b)
print({**a, **b})
c = a.copy()
c |= b
print(c) dict views, reversed, and sorting
reversed(d)yields keys in reverse insertion order (3.8+).- Sort by key:
sorted(d); by value:sorted(d, key=d.get)orsorted(d.items(), key=lambda kv: kv[1]). - Views support set-like ops:
d.keys() & other.keys().
scores = {"Ada": 90, "Bob": 75, "Cia": 88}
print(list(reversed(scores)))
print(sorted(scores))
print(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
print(scores.keys() & {"Ada", "Zoe"}) collections helpers for dicts
defaultdict(factory)auto-creates missing keys via the factory.Countercounts hashables;OrderedDictis rarely needed now that dicts keep order.ChainMapsearches multiple mappings in order without merging copies.
from collections import defaultdict, Counter, ChainMap
dd = defaultdict(int)
for ch in "mississippi":
dd[ch] += 1
print(dict(dd))
print(Counter("mississippi"))
base = {"theme": "light", "lang": "en"}
user = {"theme": "dark"}
print(dict(ChainMap(user, base))) Tricky Interview Points
Q1) What is a Python dictionary?
Answer A mutable mapping of unique hashable keys to values with average O(1) lookup, insertion, and deletion.
Q2) Why must dict keys be hashable?
Answer The dict uses a hash table. Keys must have a stable hash and consistent equality so buckets stay valid. Mutable types like list/dict are unhashable by default.
Q3) Difference between d[key] and d.get(key)?
Answer d[key] raises KeyError if missing; d.get(key) returns None (or a provided default) without raising.
Q4) Does dict preserve order?
Answer Yes, since CPython 3.6 (language guarantee from 3.7): iteration follows insertion order.
Q5) What does setdefault do?
Answer If the key exists, return its value; otherwise insert the default and return that default. Useful for grouping into lists.
Q6) Shallow vs deep copy of a dict?
Answer copy() duplicates the top-level mapping only; nested mutables are shared. copy.deepcopy recursively clones nested objects.
Q7) How do you merge two dicts?
Answer Use a | b / a |= b (3.9+), {**a, **b}, or a.update(b). Later keys overwrite earlier ones on conflict.
Q8) What does popitem return?
Answer In 3.7+ it removes and returns the last inserted (key, value) pair in LIFO order.
Q9) Can a tuple be a dict key?
Answer Yes if every element is hashable. A tuple containing a list cannot be a key.
Q10) Time complexity of dict operations?
Answer Average case O(1) for get/set/delete; worst case can degrade but is rare with good hashes. Membership in is also average O(1).
Q11) keys()/values()/items() — lists or views?
Answer They return dynamic views tied to the dict. Converting with list() snapshots the current contents.
Simple Programs
Word frequency counter
text = "to be or not to be that is the question"
freq = {}
for word in text.split():
freq[word] = freq.get(word, 0) + 1
print(sorted(freq.items(), key=lambda kv: (-kv[1], kv[0]))) Invert a dictionary (unique values)
grades = {"Ada": "A", "Bob": "B", "Cia": "A"}
inverted = {}
for name, g in grades.items():
inverted.setdefault(g, []).append(name)
print(inverted) Nested marks report
students = {
"Ada": {"math": 90, "sci": 85},
"Bob": {"math": 70, "sci": 88},
}
for name, subjects in students.items():
avg = sum(subjects.values()) / len(subjects)
print(f"{name}: avg={avg:.1f}") Merge configs with precedence
defaults = {"host": "localhost", "port": 8000, "debug": False}
env = {"port": 9000}
cli = {"debug": True}
config = defaults | env | cli
print(config) Phone book CRUD demo
book = {}
def add(name, phone):
book[name] = phone
def find(name):
return book.get(name, "not found")
def delete(name):
return book.pop(name, None)
add("Ada", "111")
add("Bob", "222")
print(find("Ada"), find("Zoe"))
delete("Bob")
print(book) Problem Solving Tricks
- Prefer
d.get(k, default)over try/except KeyError for simple missing-key defaults. - Build a dict from parallel lists:
dict(zip(keys, values)). - Swap keys/values when values are unique:
{v: k for k, v in d.items()}. - Use
d |= otherto update in place with merge syntax (3.9+). collections.Counterbeats hand-rolled counting for multiset math (+,-,most_common).- Check subset of keys with view ops:
needed <= d.keys(). - Avoid using floats as keys when equality is fuzzy; prefer integers or decimals.
- For JSON-like trees, nest dicts/lists and validate with typed helpers rather than deep chained
[]alone. - Remember
True == 1andFalse == 0can collide as keys — avoid mixing bools with ints as keys.
Practice Programs List
- Build a grocery bill dict (item → qty) and compute total with a price dict.
- Write a function that merges N dicts left-to-right (later wins).
- Group a list of (city, name) pairs into city → [names].
- Count character frequencies and print the top 3 letters.
- Safely read
user["address"]["zip"]with nested.getdefaults. - Deep-copy a nested dict and prove nested lists are independent.
- Sort a marks dict by score descending and print a rank list.
- Implement a tiny LRU sketch using dict order +
move_to_endvia pop/reinsert. - Convert a list of employee dicts into id → employee mapping.
- Write tests for KeyError vs get vs setdefault behavior.
- Invert a many-to-one dict into value → [keys] without losing duplicates.