Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

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:

python
pet = {"name": "Max", "age": 3, "animal": "dog"}
print(pet)
text
{'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:

python
my_dict = {}

Accessing Values

To get a value out of a dictionary, use square brackets with the key name:

python
pet = {"name": "Max", "age": 3, "animal": "dog"}
print(pet["name"])
print(pet["age"])
text
Max
3

Be careful! If you try to access a key that doesn't exist, you'll get an error:

python
pet = {"name": "Max", "age": 3}
print(pet["color"]) # KeyError! "color" doesn't exist

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:

python
pet = {"name": "Max", "age": 3}
print(pet.get("name", "unknown"))
print(pet.get("color", "unknown"))
text
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:

python
pet = {"name": "Max", "age": 3}
pet["color"] = "brown" # adds a new key
pet["age"] = 4 # updates an existing key
print(pet)
text
{'name': 'Max', 'age': 4, 'color': 'brown'}

Removing Items

Use del to remove a key-value pair from a dictionary:

python
pet = {"name": "Max", "age": 3, "color": "brown"}
del pet["age"]
print(pet)
text
{'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
python
pet = {"name": "Max", "age": 3, "color": "brown"}
print(list(pet.keys()))
print(list(pet.values()))
print(list(pet.items()))
text
['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:

python
pet = {"name": "Max", "age": 3, "color": "brown"}
for key, value in pet.items():
print(key, "->", value)
text
name -> Max
age -> 3
color -> brown

You can also loop through just the keys:

python
pet = {"name": "Max", "age": 3}
for key in pet.keys():
print(key, "is", pet[key])
text
name is Max
age is 3

Checking if a Key Exists

Use the in keyword to check whether a key is in the dictionary:

python
pet = {"name": "Max", "age": 3}
if "name" in pet:
print("We know the pet's name!")
if "color" not in pet:
print("We don't know the color.")
text
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:

python
classroom = {
"Alice": {"age": 10, "grade": "5th"},
"Bob": {"age": 11, "grade": "5th"}
}
print(classroom["Alice"]["age"])
text
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!