root@vm-learning
~
$
open
ch-2-13
UNIT 2 ▪ CHAPTER 13
19
Dictionaries
Key · Value · Access · Mutability · Traversal · Methods
A dictionary (
dict) is an unordered-by-index, mutable collection of key → value pairs, written inside curly braces { }. Each key must be unique and immutable (typically a string, number or tuple); values can be any type. Instead of looking items up by a numeric index the way lists and tuples do, you look them up by their key — just like finding a word's meaning in a printed dictionary. That's where the name comes from.
Five properties of a Python dict:
- Key-based access —
d["name"]notd[0]. - Mutable — you can add, modify or delete pairs after creation.
- Keys must be unique & immutable — strings, numbers, tuples ✓ · lists, other dicts ❌.
- Values can be anything — int, str, list, even another dict.
- Order preserved — since Python 3.7, a dict remembers the order in which keys were inserted (so iteration is predictable).
Learning Outcome 1: Create dictionaries and access items using keys.
19.1 Creating a Dictionary
| Form | Example |
|---|---|
Literal with { } | student = {"name": "Kavya", "roll": 22, "marks": 91} |
| Empty dict | d = {} or d = dict() |
dict() with keyword args | dict(name="Kavya", roll=22) |
dict() from a list of 2-tuples | dict([("a", 1), ("b", 2)]) → {'a': 1, 'b': 2} |
From parallel iterables with zip | dict(zip(["a","b","c"], [1,2,3])) |
All keys the same value — fromkeys | dict.fromkeys(["x","y","z"], 0) → {'x':0,'y':0,'z':0} |
Visualising a dict — student record:
19.2 Accessing an Item
Fetch a value by putting its key inside square brackets. If the key is not in the dict, Python raises KeyError.
student = {"name": "Kavya", "roll": 22, "marks": 91}
print(student["name"]) # Kavya
print(student["roll"]) # 22
# print(student["age"]) ❌ KeyError: 'age'
19.2.1 Safe access — get(key, default)
get() is the safer cousin of [ ]: if the key is missing it returns None (or a fall-back you supply) without raising an error.
print(student.get("name")) # Kavya print(student.get("age")) # None print(student.get("age", "N/A")) # N/A
19.2.2 Test for a key — in
print("name" in student) # True — tests KEYS, not values print("Kavya" in student) # False print("Kavya" in student.values()) # True — explicit values check
Learning Outcome 2: Modify a dictionary (add, update, delete) and traverse it using loops.
19.3 Dictionaries Are Mutable
A dict can be changed in place: adding a new key, replacing an existing key's value, or removing a key.
student = {"name": "Kavya", "roll": 22}
# Add a new key — just assign to it
student["marks"] = 91
student["age"] = 16
print(student)
# {'name': 'Kavya', 'roll': 22, 'marks': 91, 'age': 16}
# Modify an existing key — exactly the same syntax
student["roll"] = 23
print(student["roll"]) # 23
# Delete a key-value pair
del student["age"]
print(student)
# {'name': 'Kavya', 'roll': 23, 'marks': 91}
Assigning to
d[key] adds the pair if the key isn't already there, and updates the value if it is. There is no separate "add" syntax.
19.4 Traversing a Dictionary
Four common loops. By default, looping over a dict iterates over its keys.
prices = {"apple": 40, "banana": 10, "mango": 60}
# 1 — over keys (default)
for k in prices:
print(k) # apple, banana, mango
# 2 — over keys explicitly
for k in prices.keys():
print(k, prices[k])
# 3 — over values
for v in prices.values():
print(v) # 40, 10, 60
# 4 — over key-value pairs (most useful)
for k, v in prices.items():
print(f"{k}: ₹{v}") # apple: ₹40 …
Learning Outcome 3: Apply the built-in functions and methods of a dict.
19.5 Built-in FUNCTIONS that work on Dicts
| Function | Effect | Example (p = {"a":1,"b":2,"c":3}) |
|---|---|---|
len(d) | Number of key-value pairs | 3 |
dict(iter) | Construct a dict from an iterable of pairs / keyword args | dict(a=1, b=2) |
max(d) | Largest key (not value) | 'c' |
min(d) | Smallest key | 'a' |
sorted(d) | List of keys in sorted order | ['a', 'b', 'c'] |
sum(d) | Sum of the keys (rarely useful) | works only if keys are numeric |
max(d, key=d.get) is a common idiom: "find the key with the largest value". Useful for "who scored the highest?" style problems.
19.6 Dictionary METHODS
The CBSE dict-method families:
19.6.1 The "view" methods — keys(), values(), items()
| Method | Returns | Example (p = {"a":1,"b":2}) |
|---|---|---|
keys() | All keys, as a view object | dict_keys(['a', 'b']) |
values() | All values, as a view object | dict_values([1, 2]) |
items() | All key-value pairs as 2-tuples, as a view | dict_items([('a',1), ('b',2)]) |
The three views are live: if the dict changes, the views reflect the change automatically. Wrap in list() if you need a snapshot.
p = {"a":1, "b":2}
v = p.values()
p["c"] = 3
print(list(v)) # [1, 2, 3] — view already reflects the new item
19.6.2 Access & add — get, setdefault, update
| Method | Effect |
|---|---|
get(key, default=None) | Return d[key] if it exists, else the default. No error. |
setdefault(key, default) | If key is missing, insert it with default. Always returns the final value. Useful for "initialise-if-needed" idiom. |
update(other) | Merge other (another dict, or keyword args) into d — adding new keys, overwriting existing ones. |
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1 # 0 when first seen, else prev count
print(counts) # {'b': 1, 'a': 3, 'n': 2}
# Merging two dicts
p = {"a":1, "b":2}
p.update({"b":20, "c":3}) # 'b' overwritten, 'c' added
print(p) # {'a': 1, 'b': 20, 'c': 3}
19.6.3 Remove — pop, popitem, clear, del
| Call | Effect | Returns |
|---|---|---|
d.pop(key) | Remove key and return its value. KeyError if missing. | removed value |
d.pop(key, default) | Same, but return default if key is missing (no error). | value or default |
d.popitem() | Remove and return the last inserted pair. | 2-tuple (k, v) |
d.clear() | Empty the dict in place. | None |
del d[key] | Statement — delete one pair. Error if key missing. | — |
p = {"a":1, "b":2, "c":3}
print(p.pop("a")) # 1 — returns the removed value
print(p) # {'b': 2, 'c': 3}
print(p.popitem()) # ('c', 3) — last inserted pair
print(p) # {'b': 2}
p.clear()
print(p) # {}
19.6.4 Construct — fromkeys & copy
# fromkeys — same default value for many keys attendance = dict.fromkeys(["Mon", "Tue", "Wed"], True) print(attendance) # {'Mon': True, 'Tue': True, 'Wed': True} # copy — independent shallow copy a = {"x": 1, "y": 2} b = a.copy() b["z"] = 3 print(a) # {'x': 1, 'y': 2} — unchanged print(b) # {'x': 1, 'y': 2, 'z': 3}
19.6.5 Cheat sheet — every CBSE method & function at a glance
| Need | Code |
|---|---|
| Empty dict | d = {} |
| Number of pairs | len(d) |
| Read a value safely | d.get(k, default) |
| Add or overwrite | d[k] = v |
| Add only if missing | d.setdefault(k, default) |
| Merge two dicts | d.update(other) |
| Key exists? | k in d |
| Delete a pair | del d[k] or d.pop(k) |
| Pop last inserted | d.popitem() |
| Empty everything | d.clear() |
| Independent copy | d.copy() |
| All keys / values / pairs | d.keys() · d.values() · d.items() |
| Sorted list of keys | sorted(d) |
| Max / min of keys | max(d) · min(d) |
| Key with highest value | max(d, key=d.get) |
| Same default for many keys | dict.fromkeys(keys, default) |
Learning Outcome 4: Write the CBSE suggested programs using a dictionary.
19.7 Worked Programs
19.7.1 Count the frequency of each character in a string
The classic use of a dict: the key is the character, the value is the running count.
s = input("Enter a string: ") freq = {} for ch in s: freq[ch] = freq.get(ch, 0) + 1 for ch, c in freq.items(): print(f"{ch!r} appears {c} time(s)")Sample run for
"banana":
'b' appears 1 time(s) 'a' appears 3 time(s) 'n' appears 2 time(s)
Python's
collections module has a ready-made Counter that does the same in one line:
from collections import Counter print(Counter("banana")) # Counter({'a': 3, 'n': 2, 'b': 1})For exam work, stick with the manual version shown above — it shows the logic.
19.7.2 Employee name → salary dictionary
Build a dict mapping employee names to their salaries, then look up values and answer queries.
# employees.py — name → salary dictionary salary = { "Aarav": 45000, "Kavya": 52000, "Ishan": 38000, "Priya": 60000, "Rohan": 47500 } print("Number of employees:", len(salary)) print("Total salary bill : ₹", sum(salary.values())) print("Average salary : ₹", sum(salary.values()) / len(salary)) print("Highest paid :", max(salary, key=salary.get)) print("Lowest paid :", min(salary, key=salary.get)) # Search by name name = input("Search name: ") if name in salary: print(f"{name} earns ₹{salary[name]}") else: print(name, "is not in the records") # Give everyone a 10% raise for k in salary: salary[k] = int(salary[k] * 1.10) print("After 10% raise:", salary)Sample output:
Number of employees: 5
Total salary bill : ₹ 242500
Average salary : ₹ 48500.0
Highest paid : Priya
Lowest paid : Ishan
Search name: Kavya
Kavya earns ₹52000
After 10% raise: {'Aarav': 49500, 'Kavya': 57200, 'Ishan': 41800, 'Priya': 66000, 'Rohan': 52250}
19.7.3 Bonus — Words longer than a given length
sentence = "Python dictionaries are really useful" n = 6 counts = {} for word in sentence.split(): if len(word) >= n: counts[word] = len(word) print(counts) # {'Python': 6, 'dictionaries': 12, 'really': 6, 'useful': 6}
19.8 Comparing the Four Collections
| Property | String | List | Tuple | Dict |
|---|---|---|---|---|
| Brackets | " " | [ ] | ( ) | { } |
| Ordered | Yes | Yes | Yes | Yes (since 3.7) |
| Mutable | No | Yes | No | Yes |
| Indexed by | integer | integer | integer | key |
| Duplicate items? | OK | OK | OK | keys must be unique; values can repeat |
| Typical use | text | variable collection | fixed record | key → value mapping |
📌 Quick Revision — Chapter 19 at a Glance
- Dict = collection of key → value pairs in
{ }. Keys must be unique & immutable (str, num, tuple). Values can be anything. - Creation: literal
{"k": v}·dict()· keyword args · fromzip·dict.fromkeys(seq, v). - Access:
d[key]raisesKeyErrorif missing.d.get(key, default)never raises. key in dtests keys. Test values withv in d.values().- Mutable:
d[k] = vadds-or-overwrites in one step. Remove withdel d[k],d.pop(k),d.popitem(),d.clear(). - Iteration:
for k in d(keys) ·for v in d.values()·for k, v in d.items(). - View methods (
keys,values,items) return live views — wrap inlist()for a snapshot. - Construct/merge:
dict(),fromkeys,update(other),copy(). - Built-in functions operate on keys:
len(d),max(d),min(d),sorted(d). Trick:max(d, key=d.get)→ key with biggest value. - CBSE programs:
- Character-frequency counter —
d[ch] = d.get(ch, 0) + 1. - Employee name → salary — lookup, total, average, highest paid (
max(d, key=d.get)), give-a-raise loop.
- Character-frequency counter —
- Dict vs List vs Tuple: dict indexed by key, not position. Use when you need labelled data.