Intermediate âĸ Python
Dictionaries
đ What is a Dictionary?
A dictionary stores information in pairs. Each pair has a key (like a label) and a value (the information). We write a dictionary with curly brackets { }, and put a colon between each key and its value. It works like a real dictionary, where you look up a word to find its meaning.
pet = {"name": "Buddy", "animal": "dog", "age": 3}
print(pet)
print(len(pet)){'name': 'Buddy', 'animal': 'dog', 'age': 3}
3đ Everything in Dictionaries
Learn how to store information in pairs of keys and values, look things up, change them, loop through them, and build simple nested dictionaries. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
đ What is a Dictionary?
A dictionary stores information in pairs. Each pair has a key (like a label) and a value (the information). We write a dictionary with curly brackets { }, and put a colon between each key and its value. It works like a real dictionary, where you look up a word to find its meaning.
pet = {"name": "Buddy", "animal": "dog", "age": 3} print(pet) print(len(pet))đ Looking Up Values
To get a value, put its key inside square brackets after the dictionary name. Python finds the key and gives you the value that goes with it. Keys must match exactly, including capital letters.
scores = {"Ana": 90, "Ben": 75, "Cleo": 88} print(scores["Ana"]) print(scores["Cleo"])âī¸ Adding and Changing Values
Dictionaries can change! To add a new pair, write a new key in square brackets and give it a value. If the key already exists, the old value is replaced with the new one.
player = {"name": "Kai", "level": 1} player["level"] = 2 player["coins"] = 50 print(player)đĄī¸ Safe Lookups with get() and in
If you look up a key that is not in the dictionary with square brackets, Python gives an error. The get() method is safer: it gives back None, or a backup value you choose, when the key is missing. The in keyword checks if a key exists and gives True or False.
stock = {"apples": 5, "pears": 2} print(stock.get("apples")) print(stock.get("grapes")) print(stock.get("grapes", 0)) print("pears" in stock) print("grapes" in stock)đ Looping with items()
The items() method lets a for loop go through every key and value together. We use two variables in the loop, one for the key and one for the value. This is great for printing everything in a dictionary neatly.
ages = {"Mia": 10, "Leo": 12, "Zoe": 9} for name, age in ages.items(): print(f"{name} is {age}")đī¸ Dictionaries Inside Dictionaries
A dictionary value can be another dictionary! This is called a nested dictionary. It helps you store lots of details about many things. Use two sets of square brackets to reach the inner value.
pets = { "Buddy": {"animal": "dog", "age": 3}, "Whiskers": {"animal": "cat", "age": 5} } print(pets["Buddy"]["animal"]) print(pets["Whiskers"]["age"])
