Python Tutorial
Python Dictionaries and Dictionary Methods
A dictionary maps keys to values: a student id to a name, a product code to a price, a word to its count. Lookups by key are fast (O(1) on average), dictionaries keep insertion order (since Python 3.7), and JSON data from APIs maps directly onto them.
This lesson covers creating dictionaries, reading and updating values safely, every dictionary method — get, keys, values, items, update, pop, popitem, setdefault, fromkeys, clear, copy — merging, dict comprehensions and nested dictionaries.
Creating and Accessing
Create with braces {"name": "Asha", "age": 24}, dict(name="Asha"), dict(zip(keys, values)) or a comprehension. Keys must be hashable and unique; values can be anything. d[key] raises KeyError for missing keys, while d.get(key, default) returns a default. Assigning d[key] = value adds or updates.
The Methods
Every dict method:
get(k, default)— safe read.keys(),values(),items()— live views for iteration.update(other)— merge in another dict or key/value pairs;d1 | d2andd1 |= d2also merge (3.9+).pop(k, default)— remove and return a value;popitem()removes the last inserted pair.setdefault(k, default)— return the value, inserting the default if the key is missing.fromkeys(keys, value)— class method creating a dict with the same value for each key.clear()— remove everything;copy()— shallow copy.
Iterating and Transforming
Iterating a dict yields keys; use .items() for key/value pairs. Dict comprehensions build or filter dictionaries in one expression. Sort by value with sorted(d.items(), key=lambda kv: kv[1]). Do not add or remove keys while iterating over a dict.
Nested Dictionaries
Real data is often nested — an API response with a user containing an address containing a city. Access with chained keys (data["user"]["address"]["city"]) or safely with chained get calls. For counting and grouping, collections.Counter and defaultdict (see the collections lesson) are even more convenient.
Examples
Creating, reading, adding and updating
student = {"name": "Asha", "age": 24, "courses": ["Python"]}
print(student["name"], student.get("city"), student.get("city", "Unknown"))
student["city"] = "Pune"
student["age"] += 1
student["courses"].append("SQL")
print(student)
print(dict(zip(["a", "b"], [1, 2])), dict(x=1, y=2))
try:
student["email"]
except KeyError as e:
print("KeyError:", e)
Asha None Unknown
{'name': 'Asha', 'age': 25, 'courses': ['Python', 'SQL'], 'city': 'Pune'}
{'a': 1, 'b': 2} {'x': 1, 'y': 2}
KeyError: 'email'
Every dictionary method
prices = {"pen": 10, "book": 250}
print(list(prices.keys()), list(prices.values()), list(prices.items()))
prices.update({"bag": 899, "pen": 12})
print("update :", prices)
removed = prices.pop("book")
print("pop :", removed, prices, prices.pop("lamp", "not found"))
print("popitem :", prices.popitem(), prices)
print("setdefault:", prices.setdefault("ink", 40), prices.setdefault("pen", 99), prices)
print("fromkeys :", dict.fromkeys(["a", "b", "c"], 0))
copy_ = prices.copy()
prices.clear()
print("clear :", prices, "copy:", copy_)
print("merge :", {"a": 1, "b": 2} | {"b": 3, "c": 4})
['pen', 'book'] [10, 250] [('pen', 10), ('book', 250)]
update : {'pen': 12, 'book': 250, 'bag': 899}
pop : 250 {'pen': 12, 'bag': 899} not found
popitem : ('bag', 899) {'pen': 12}
setdefault: 40 12 {'pen': 12, 'ink': 40}
fromkeys : {'a': 0, 'b': 0, 'c': 0}
clear : {} copy: {'pen': 12, 'ink': 40}
merge : {'a': 1, 'b': 3, 'c': 4}
Iterating, sorting by value, comprehensions and grouping
scores = {"Asha": 91, "Ravi": 72, "Meera": 88, "Kiran": 65}
for name, score in scores.items():
print(f"{name}: {score}")
top = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
print("Top 2:", top)
passed = {n: s for n, s in scores.items() if s >= 70}
print(passed)
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for w in words:
groups.setdefault(w[0], []).append(w)
print(groups)
Asha: 91
Ravi: 72
Meera: 88
Kiran: 65
Top 2: [('Asha', 91), ('Meera', 88)]
{'Asha': 91, 'Ravi': 72, 'Meera': 88}
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
Nested dictionaries (like JSON from an API)
response = {
"user": {"id": 7, "name": "Asha", "address": {"city": "Pune", "pin": "411001"}},
"orders": [{"id": 101, "total": 2999}, {"id": 102, "total": 499}],
}
print(response["user"]["address"]["city"])
print(response.get("user", {}).get("phone", {}).get("mobile", "no phone"))
print(sum(o["total"] for o in response["orders"]))
Pune
no phone
3498
Common Mistakes
- Using d[key] for keys that might be missing instead of d.get(key).
- Using mutable objects (lists) as keys.
- Changing a dict's size while iterating over it (RuntimeError).
- Using dict.fromkeys(keys, []) — every key shares the same list.
- Assuming copy() deep-copies nested values.
Key Points to Remember
- Dicts map unique hashable keys to values and keep insertion order.
- get() reads safely; assignment adds or updates.
- keys/values/items views, update or |, pop/popitem, setdefault, fromkeys, clear, copy.
- Dict comprehensions build and filter dictionaries concisely.
- Nested dicts mirror JSON; chain get() for safe access.
Practice the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.