VM-LEARNING /class.xi ·track.cs ·ch-2-13 session: 2026_27
$cd ..

~/Dictionaries

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 accessd["name"] not d[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

FormExample
Literal with { }student = {"name": "Kavya", "roll": 22, "marks": 91}
Empty dictd = {}  or  d = dict()
dict() with keyword argsdict(name="Kavya", roll=22)
dict() from a list of 2-tuplesdict([("a", 1), ("b", 2)]){'a': 1, 'b': 2}
From parallel iterables with zipdict(zip(["a","b","c"], [1,2,3]))
All keys the same value — fromkeysdict.fromkeys(["x","y","z"], 0){'x':0,'y':0,'z':0}
Visualising a dict — student record: student = {"name": "Kavya", "roll": 22, "marks": 91, "pass": True} "name" key "Kavya" value "roll" 22 "marks" 91 "pass" True Keys on the left (green) — unique & immutable. Values on the right (blue) — any type.

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

FunctionEffectExample (p = {"a":1,"b":2,"c":3})
len(d)Number of key-value pairs3
dict(iter)Construct a dict from an iterable of pairs / keyword argsdict(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: Dictionary Methods (CBSE Class XI set) View keys() values() items() live "views" Access / Add get(k, default) setdefault(k, v) update(other) Remove pop(k) popitem() clear() del d[k] — statement Construct dict(...) fromkeys(seq, v) copy() Built-in fns len · max · min sorted called as fn(d) operate on KEYS All methods (except copy) modify the dict in place; functions return a new value.

19.6.1 The "view" methods — keys(), values(), items()

MethodReturnsExample (p = {"a":1,"b":2})
keys()All keys, as a view objectdict_keys(['a', 'b'])
values()All values, as a view objectdict_values([1, 2])
items()All key-value pairs as 2-tuples, as a viewdict_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

MethodEffect
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

CallEffectReturns
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

NeedCode
Empty dictd = {}
Number of pairslen(d)
Read a value safelyd.get(k, default)
Add or overwrited[k] = v
Add only if missingd.setdefault(k, default)
Merge two dictsd.update(other)
Key exists?k in d
Delete a pairdel d[k]  or  d.pop(k)
Pop last insertedd.popitem()
Empty everythingd.clear()
Independent copyd.copy()
All keys / values / pairsd.keys() · d.values() · d.items()
Sorted list of keyssorted(d)
Max / min of keysmax(d) · min(d)
Key with highest valuemax(d, key=d.get)
Same default for many keysdict.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

PropertyStringListTupleDict
Brackets" "[ ]( ){ }
OrderedYesYesYesYes (since 3.7)
MutableNoYesNoYes
Indexed byintegerintegerintegerkey
Duplicate items?OKOKOKkeys must be unique; values can repeat
Typical usetextvariable collectionfixed recordkey → 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 · from zip · dict.fromkeys(seq, v).
  • Access: d[key] raises KeyError if missing. d.get(key, default) never raises.
  • key in d tests keys. Test values with v in d.values().
  • Mutable: d[k] = v adds-or-overwrites in one step. Remove with del 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 in list() 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.
  • Dict vs List vs Tuple: dict indexed by key, not position. Use when you need labelled data.
🧠Practice Quiz — test yourself on this chapter