A list keeps things in order and finds them by position. But often you want to find a value by a name: the price of a product, the city of a customer, the number of times a word appears. A dictionary (dict) is made for that. It is one of the most useful tools in Python, and you will use it in almost every real program.
Dictionaries
A dictionary stores key and value pairs inside curly braces: {"name": "Notebook", "price": 120}. You look up a value by its key, like product["price"]. Keys are usually text or numbers and must be unique. Values can be anything, including lists and other dictionaries. Study this program and its output.
product = {"name": "Notebook", "price": 120, "stock": 15}
print(product["name"], product.get("colour", "no colour"))
product["stock"] -= 3
product["category"] = "Stationery"
print(product)
for key, value in product.items():
print(f"{key}: {value}")
# Counting words
text = "the cat and the dog and the bird"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
# A list of dictionaries, like rows of a table
orders = [
{"id": 1, "city": "Pune", "amount": 450},
{"id": 2, "city": "Delhi", "amount": 300},
{"id": 3, "city": "Pune", "amount": 150},
]
pune_total = sum(o["amount"] for o in orders if o["city"] == "Pune")
print("Pune total:", pune_total)
# Tuples and sets
point = (3, 4)
x, y = point
print(x, y)
cities = {"Pune", "Delhi", "Pune"}
print(len(cities), "Delhi" in cities)
unique = sorted(set([3, 1, 3, 2, 1]))
print(unique)
Notebook no colour
{'name': 'Notebook', 'price': 120, 'stock': 12, 'category': 'Stationery'}
name: Notebook
price: 120
stock: 12
category: Stationery
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
Pune total: 600
3 4
2 True
[1, 2, 3]
product["stock"]reads a value. It raises aKeyErrorif the key does not exist.product.get("colour", "no colour")returns a default value instead of an error, andgetwithout a default returnsNone.product["stock"] -= 3changes a value. Assigning to a new key, likeproduct["category"], adds it..items()gives key and value pairs for a loop..keys()and.values()give only keys or values.del product["stock"]removes a key."price" in productchecks whether a key exists.- Since Python 3.7, a dictionary remembers the order in which keys were added.
A very common pattern: counting
The loop that counts words is a pattern you will use again and again. For each word, counts.get(word, 0) + 1 means: take the current count, or 0 if the word is new, and add one. The output shows the three times, and and twice. Later you will meet collections.Counter, which does this in one line, but writing it once by hand is the best way to understand it.
Lists of dictionaries: data like a table
Rows of a spreadsheet or a database are often a list of dictionaries, where each dictionary is one row and each key is a column name. That is also very close to JSON, the format used by web services. You can filter and add up the rows with loops and comprehensions. The line sum(o["amount"] for o in orders if o["city"] == "Pune") adds the amounts of the orders from Pune only, and the program printed 600 (450 plus 150).
Tuples
A tuple is like a list that cannot be changed after it is made. It is written with round brackets: point = (3, 4). Use tuples for small fixed groups of values, such as a point on a map or a name and a score. You can unpack a tuple into variables in one line: x, y = point. Functions often return several values as a tuple. You will see that in the next lesson.
Sets
A set holds unique values, with no order and no duplicates. {"Pune", "Delhi", "Pune"} has only two items. Sets are fast at checking whether something is in them, and they are good for removing duplicates: sorted(set([3, 1, 3, 2, 1])) gives [1, 2, 3]. An empty set is written set(), because {} makes an empty dictionary.
Which one should I use?
- List: an ordered group that may change, such as the lines of a file.
- Dictionary: look up by name or id, such as a product by its code.
- Tuple: a small fixed group, such as coordinates.
- Set: unique values and quick membership checks.
Common mistakes
- Using a key that does not exist and getting a
KeyError. Usegetor check within. - Using a list as a key. Keys must be fixed values such as text, numbers or tuples.
- Writing
{}and expecting a set. - Changing a dictionary while you loop over it. Loop over
list(my_dict)if you need to remove keys.
Your task
- Make a dictionary for yourself with keys name, city and skills (a list). Print each key and value on its own line.
- Write a program that counts how many times each letter appears in a word you choose, and prints the counts.
- Make a list of four order dictionaries with
id,cityandamount. Print the total for one city and the largest order. - Remove the duplicates from
[5, 3, 5, 1, 3, 9]and print the numbers in order.
How to check it worked
- For
"banana"your letter count showsathree times,ntwice andbonce. - The unique sorted list is
[1, 3, 5, 9]. - You can explain the difference between
product["x"]andproduct.get("x").