KTU S1

Dictionaries

By the end you should be able to: Create and use Python dictionaries, iterate over keys, values and items, and recognise problems where lookup by key is the right model.

A dictionary stores key → value pairs. Where a list answers "what is at position 3?", a dictionary answers "what is stored under 'Anjali'?".

marks = {"Anjali": 87, "Rahul": 74, "Meera": 91}

marks["Anjali"]         # 87
marks["Rahul"] = 78     # update
marks["Vishnu"] = 65    # add
del marks["Meera"]      # remove
len(marks)              # 3

Keys must be immutable

Strings, numbers and tuples work. Lists and sets do not — for the reason in the tuples topic: a key that could change would make its entry unfindable.

{(10, 20): "Depot"}     # fine
{[10, 20]: "Depot"}     # TypeError

Keys are unique. Assigning to an existing key overwrites rather than adding a second entry.

Missing keys

marks["Nobody"]              # KeyError — crashes
marks.get("Nobody")          # None
marks.get("Nobody", 0)       # 0  — a default you choose
"Nobody" in marks            # False

.get() with a default is the safe form and appears constantly in real code. [ ] is right when a missing key genuinely is a bug you want to hear about.

Iterating

for name in marks:                  # keys, by default
    print(name)

for name in marks.keys():           # same thing, explicit
for score in marks.values():        # just the values
for name, score in marks.items():   # both — usually what you want
    print(f"{name}: {score}")

.items() is the one to reach for. Writing for name in marks: then marks[name] inside works but does a second lookup each pass.

Ordering

Since Python 3.7 dictionaries keep insertion order. Printing one shows keys in the order they were added. Don't rely on it for correctness, but it does mean output is predictable, unlike a set.

The counting pattern

The single most common use, and worth memorising:

text = "mississippi"
counts = {}

for ch in text:
    counts[ch] = counts.get(ch, 0) + 1

print(counts)   # {'m': 1, 'i': 4, 's': 4, 'p': 2}

counts.get(ch, 0) + 1 reads as "whatever is there, or zero if nothing, plus one". Without .get() you would need an if ch in counts check every pass.

Nested values

A dictionary's values can be anything, including lists — which is how you model one-to-many:

subjects = {
    "Anjali": ["Maths", "Python"],
    "Rahul":  ["Python"],
}

subjects["Rahul"].append("Physics")

This is the model sketched in Module 1's "formulating a model" topic, now in real syntax.

Choosing a dictionary

Reach for one when the question is "what is associated with X?" — name to marks, product code to price, roll number to attendance. If you find yourself keeping two parallel lists and matching by index, you want a dictionary instead.