>>> Python for Beginners Chapter 09 of 10

Chapter 09 ยท Collections

Dictionaries

A list is great when order matters. But sometimes you want to look things up by a label, not a position - a phone book, a price list, a student's record. That's a dictionary.

๐Ÿ“–
Real-world analogy

A dictionary is a real dictionary: you look up a word (the key) and get its meaning (the value). You don't care if "zebra" is item number 4,000 โ€” you look it up by name, instantly.

Making a dictionary

Curly braces, with key: value pairs:

student = {
    "name": "Grace",
    "age": 19,
    "course": "Computer Science"
}
print(student["name"])
print(student["course"])
Grace Computer Science

You look things up by their key (student["name"]), not by a number.

Adding and changing

prices = {"bread": 25, "milk": 18}
prices["eggs"] = 40
prices["bread"] = 30
print(prices)
print("Eggs now cost K", prices["eggs"])
{'bread': 30, 'milk': 18, 'eggs': 40} Eggs now cost K 40

Assigning to a new key adds it; assigning to an existing key updates it.

Looping over a dictionary

prices = {"bread": 30, "milk": 18, "eggs": 40}
for item in prices:
    print(f"{item} costs K{prices[item]}")
bread costs K30 milk costs K18 eggs costs K40
โœ๏ธ Try it yourself

Build a dictionary describing you: keys for name, town and age. Print a sentence about yourself using the values.

Keys must exist

Asking for a key that isn't there (prices["sugar"] when there's no sugar) causes an error. You can check first with if "sugar" in prices:.

Recap