Dictionaries
- Store key-value pairs with dict literals
{} - Look up, update, and delete entries safely
- Iterate over keys, values, and items with
.keys(),.values(),.items() - Use
.get()to avoidKeyErrorwhen accessing missing keys
Dicts back every JSON API response, Django ORM row, and pandas record. Redis, MongoDB, and even Python's own class attributes are dicts under the hood. Fluency here is non-negotiable for backend or data roles.
- Accessing a missing key with
d[k]raisesKeyError. Used.get(k)ord.get(k, default)for safe lookups. - Using mutable objects like lists as keys. Only hashable types (
str,int,tuple) work; lists raiseTypeError. - Iterating
for k in dand expecting values. That yields keys; used.items()for pairs.
A dict maps a key to a value. Keys must be unique and immutable (strings, numbers, tuples).
Three things you'll use constantly
d[key]— read or writed.get(key, default)— read without crashing if missingd.items()— iterate over(key, value)pairs
Try it
- Add three more items to
prices. - Print the total cost of one of each fruit using
sum(prices.values()).
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
The dict
prices = {"apple": 30, "banana": 10, "mango": 80}maps fruit to rupees. Print the price ofmango. Expected last line:80. - Exercise 2
For the same
pricesdict, compute and print the total cost if you buy one of each fruit — expected:120. - Exercise 3
From
words = ["apple", "kiwi", "banana", "fig"], build a dictionary mapping each word to its length, then print the dictionary. Expected includes:{'apple': 5, 'kiwi': 4, 'banana': 6, 'fig': 3}.