Back to Study Material Python

Dictionary

A dictionary maps keys to values. Create one with curly braces: person = {"name": "Alice", "age": 30}. Keys must be hashable (strings, numbers, and tuples ...

Dictionary

Dictionary Basics

A dictionary maps keys to values. Create one with curly braces: person = {"name": "Alice", "age": 30}. Keys must be hashable (strings, numbers, and tuples of hashables). Values can be any type. Access a value: person["name"] gives "Alice". Add or update: person["email"] = "[email protected]". Check membership: "age" in person returns True (tests keys, not values). Delete a key: del person["age"] or use person.pop("age"), which also returns the removed value.

Dictionary Methods

keys() returns a view of all keys. values() returns a view of all values. items() returns a view of (key, value) pairs. get(key, default) returns the value for a key without raising KeyError if missing — the second argument is returned instead (default None). update(other_dict) merges another dictionary into the current one. setdefault(key, default) returns the value if key exists, otherwise inserts the key with the default value and returns it. clear() removes all items.

Iterating over Dictionaries

for key in d: iterates over keys. for val in d.values(): iterates over values. for k, v in d.items(): iterates over key-value pairs — this is the most commonly used pattern. Python 3.7+ guarantees that dictionaries maintain insertion order. Dictionary views (keys(), values(), items()) are dynamic — they reflect changes to the dictionary in real time, unlike a snapshot. To iterate safely while modifying, iterate over list(d.keys()).

Dictionary Comprehensions

Like list comprehensions, dictionary comprehensions build dictionaries concisely. {k: v for k, v in pairs} where pairs is a list of (key, value) tuples. Example: square_map = {x: x**2 for x in range(6)} gives {0:0, 1:1, 2:4, 3:9, 4:16, 5:25}. Add a filter: {k: v for k, v in d.items() if v > 0} creates a new dict with only positive values. Comprehensions are faster than building a dict with a loop and d[k] = v.

Nested Dictionaries

Dictionary values can themselves be dictionaries, creating nested structures: users = {"alice": {"age": 30, "role": "admin"}, "bob": {"age": 25, "role": "user"}}. Access nested values: users["alice"]["role"] gives "admin". Update a nested value: users["bob"]["age"] = 26. This pattern models hierarchical data like JSON. For deeply nested access where intermediate keys might be missing, use .get() chains or the third-party glom library to avoid KeyError.

Exam Tip

Dictionary exam traps: d["missing_key"] raises KeyError; d.get("missing_key") returns None. Another: what does d.keys() return — a list? No, it returns a dict_keys view object in Python 3. To get a list: list(d.keys()). Also know that from Python 3.9+, you can merge dictionaries with |: merged = d1 | d2, and update in place with |=. The walrus operator with .get() is a common pattern: if val := d.get("key"): use_val(val). These modern idioms show Python 3 fluency.