Skip to main content

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.

L1

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, tuple of 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.
IdeaMeaningExample
KeyUnique label'name', 101
ValueData stored under the key'Ada', 95
PairOne mapping'city': 'Pune'
Empty dictNo 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).
Featurelisttuplesetdictionary
Literal[1, 2](1, 2){1, 2}{'a': 1}
Empty form[]()set(){} / dict()
Ordered?YesYesNo (do not rely on order)Yes (insertion order, 3.7+)
Mutable?YesNoYesYes
Allows duplicates?YesYesNo (unique elements)Keys unique; values may repeat
Indexing x[i]?YesYesNoBy key: d[key] (not position)
Slicing?YesYesNoNo
Hashable / dict key?NoYes (if elements hashable)No (frozenset yes)No (keys must be hashable)
Typical in costO(n)O(n)≈ O(1)≈ O(1) on keys
Main methods ideaMany (append, sort, …)Only count, indexAlgebra + add/removeget, update, keys, …
Best forGrowable ordered dataFixed records / multi-returnUniques & fast membershipNamed lookup / mappings
Real-life exampleTodo list, playlistGPS (lat, lon), RGBUnique tags, visitor IDsPhone 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) or dict([("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), not d.len().
  • Iterating a dict yields **keys**. Use d.values() / d.items() when you need values or pairs.
FunctionWhat it doesExampleResult
len(d)Number of keyslen({"a": 1, "b": 2})2
dict(...)Build a dictdict(x=1, y=2){"x": 1, "y": 2}
dict.fromkeys(keys, default)Same default for every keydict.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 keyssorted({"b": 1, "a": 2})["a", "b"]
sorted(d, key=d.get)Keys sorted by valuesorted({"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 checkisinstance({}, dict)True
zip(keys, values) + dictBuild from parallel sequencesdict(zip(["a","b"], [1,2])){"a": 1, "b": 2}

Access and safe get

  • d[key] raises KeyError if missing. Prefer d.get(key) / d.get(key, default).
  • key in d checks existence without raising.
  • **Real-life:** asking a receptionist for a room — get a default “not found” instead of crashing.
APIWhat it doesExampleNotes
d[key]Get valued["tea"]Raises KeyError if missing
d.get(key)Safe getd.get("juice")Returns None if missing
d.get(key, default)Safe get with defaultd.get("juice", 0)Returns default if missing
key in dMembership on keys"tea" in dDoes not check values
key not in dMissing-key test"juice" not in dBoolean
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] = value inserts 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 / opWhat it doesExampleNotes
d[key] = valueInsert or overwrited["a"] = 1Most common write
d.update(other)Merge mapping / pairsd.update({"b": 2})Later keys win
d |= otherIn-place merge (3.9+)d |= {"c": 3}Like update
d | otherNew merged dict (3.9+)d | {"c": 3}Originals unchanged
del d[key]Delete keydel d["a"]Raises if missing
d.pop(key)Remove and return valued.pop("a")Raises if missing
d.pop(key, default)Pop with defaultd.pop("z", None)No error if missing
d.popitem()Remove last inserted paird.popitem()Returns (key, value)
d.clear()Remove all pairsd.clear()Becomes {}
d.setdefault(key, default)Get or insert defaultd.setdefault("a", [])Returns value
d.copy()Shallow copye = 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()).
MethodWhat it doesExampleTypical use
d.keys()View of keyslist(d.keys())Iterate / test membership of keys
d.values()View of valueslist(d.values())Aggregate values (sum, max)
d.items()View of (key, value) pairsfor k, v in d.items()Most readable loop
list(d.items())Snapshot list of pairslist(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 inserts default and 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 prefer defaultdict(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.
CategoryCommon APIsUse when
Built-inslen, dict, sorted, reversed, zip + dictCreate, measure, order keys
Readd[key], get, inLookup without crashing
Write / merged[key]=, update, |, |=Insert or combine maps
Deletedel, pop, popitem, clearRemove pairs
Viewskeys, values, itemsIterate structure
Helperssetdefault, copy, fromkeysInitialize, group, duplicate

Nested dictionaries

  • Values can be dicts (or lists of dicts) for structured records.
  • Access with chained keys: data["user"]["email"]. Use .get carefully 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 = a aliases the same object; mutating through either name changes both.
  • Deep copy nested structures with copy.deepcopy when 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)
L2

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: 1 and 1.0 and True can 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 | other returns a new merged dict; d |= other updates in place (3.9+).
  • {**a, **b} unpacks; later keys win on conflict.
  • update mutates; | 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) or sorted(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.
  • Counter counts hashables; OrderedDict is rarely needed now that dicts keep order.
  • ChainMap searches 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)))
L3

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.

L4

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)
L5

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 |= other to update in place with merge syntax (3.9+).
  • collections.Counter beats 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 == 1 and False == 0 can collide as keys — avoid mixing bools with ints as keys.
L6

Practice Programs List

  1. Build a grocery bill dict (item → qty) and compute total with a price dict.
  2. Write a function that merges N dicts left-to-right (later wins).
  3. Group a list of (city, name) pairs into city → [names].
  4. Count character frequencies and print the top 3 letters.
  5. Safely read user["address"]["zip"] with nested .get defaults.
  6. Deep-copy a nested dict and prove nested lists are independent.
  7. Sort a marks dict by score descending and print a rank list.
  8. Implement a tiny LRU sketch using dict order + move_to_end via pop/reinsert.
  9. Convert a list of employee dicts into id → employee mapping.
  10. Write tests for KeyError vs get vs setdefault behavior.
  11. Invert a many-to-one dict into value → [keys] without losing duplicates.