What Is a Dictionary?
Imagine you have an address book where you look up someone's name to find their phone number. A dictionary in Python works the same way! It stores pairs of information: a key (like the name) and a value (like the phone number).
You create a dictionary using curly braces {} with keys and values separated by colons:
{'name': 'Max', 'age': 3, 'animal': 'dog'}Each piece of data has a label (the key) that you use to find it. The key comes first, then a colon :, then the value.
You can also start with an empty dictionary and add things later:
Accessing Values
To get a value out of a dictionary, use square brackets with the key name:
Max 3
Be careful! If you try to access a key that doesn't exist, you'll get an error:
Using .get() for Safe Access
There's a safer way to look up values. The .get() method lets you provide a default value in case the key doesn't exist:
Max unknown
Instead of crashing with an error, .get() returns the default value you provide. This is super handy!
Adding and Updating Values
You can add a new key-value pair or change an existing one using square brackets:
{'name': 'Max', 'age': 4, 'color': 'brown'}Removing Items
Use del to remove a key-value pair from a dictionary:
{'name': 'Max', 'color': 'brown'}Getting Keys, Values, and Items
Dictionaries have three helpful methods to see what's inside:
.keys()gives you all the keys.values()gives you all the values.items()gives you both together as pairs
['name', 'age', 'color']
['Max', 3, 'brown']
[('name', 'Max'), ('age', 3), ('color', 'brown')]Looping Through a Dictionary
You can use a for loop to go through all the key-value pairs. The .items() method is perfect for this:
name -> Max age -> 3 color -> brown
You can also loop through just the keys:
name is Max age is 3
Checking if a Key Exists
Use the in keyword to check whether a key is in the dictionary:
We know the pet's name! We don't know the color.
Nested Dictionaries
You can put a dictionary inside another dictionary! This is useful when each item has multiple pieces of information:
10
You use two sets of square brackets: the first to pick the outer key, and the second to pick the inner key.
Summary
Dictionaries are great for storing data that has labels! Here's a quick recap:
- Create a dictionary:
my_dict = {"key": "value"} - Access a value:
my_dict["key"] - Safe access:
my_dict.get("key", "default") - Add or update:
my_dict["new_key"] = "new_value" - Remove:
del my_dict["key"] - Get keys:
my_dict.keys() - Get values:
my_dict.values() - Get pairs:
my_dict.items() - Loop:
for key, value in my_dict.items(): - Check membership:
if "key" in my_dict: - Empty dictionary:
my_dict = {}
Now let's practice with some exercises!