Dictionaries in Python let you store data in a way that makes sense — not by index numbers, but by using keys. Each item in a dictionary is a pair: a key and a value. Instead of asking, “What’s at position 0?”, you ask, “What’s the value for this key?” This makes dictionaries perfect when you want to label your data and find things quickly.
Creating Dictionaries
To make a dictionary, use curly braces {}
and separate each key from its value with a colon. Keys must be unique and unchangeable — usually strings or numbers — while values can be anything: numbers, text, even other lists or dictionaries.
person = {
"name": "Alice",
"age": 25,
"job": "Engineer"
}
Accessing and Modifying Values
You can get the value for a key by putting the key name in square brackets. You can also update an existing key or add a completely new one. If you try to access a key that isn’t there, Python will raise a KeyError
.
print(person["name"]) # Alice
person["age"] = 26 # Update value
person["city"] = "London" # Add new key-value pair
Dictionary Methods
Python dictionaries come with helpful tools for working with their contents. You can get a list of all the keys, all the values, or all the key-value pairs using these built-in methods:
print(person.keys()) # dict_keys(['name', 'age', 'job', 'city']) print(person.values()) # dict_values(['Alice', 26, 'Engineer', 'London']) print(person.items()) # dict_items([('name', 'Alice'), ...])
Interactive Exercise: Working with Dictionaries
Let’s create a simple dictionary, then try updating and expanding it. You’ll get a feel for how flexible dictionaries can be in your code.
# Create a dictionary
student = {"name": "Bob", "grade": "A"} # Access values
print(student["name"])
# Modify values
student["grade"] = "B"
# Add a new key-value pair
student["age"] = 18
print(student)
Dictionaries are one of Python’s most powerful data types because they let you store and retrieve information quickly — and in a way that’s easy to understand. Once you start working with real-world data like user profiles, settings, or records, dictionaries will become your go-to tool.