Python Dictionaries Explained
A Python dictionary stores data as key-value pairs. It is one of the most useful built-in data types in Python.
Dictionaries are great when your data has labels such as name, age, or price. Instead of finding a value by position, you look it up by its key.
For example:
student = {"name": "Ana", "age": 20}
In this dictionary:
"name"is a key, and"Ana"is its value"age"is a key, and20is its value
If you are completely new to the term, see what a dictionary in Python is.
Quick example #
Use this example to see the most common dictionary tasks: create, read, update, add, and loop.
student = {"name": "Ana", "age": 20}
print(student["name"])
student["age"] = 21
student["city"] = "Madrid"
for key, value in student.items():
print(key, value)
Expected output:
Ana
name Ana
age 21
city Madrid
What a dictionary is #
A dictionary:
- Stores data as key-value pairs
- Uses each key to look up a value
- Works well for labeled data
- Is written with curly braces
{}
Example:
person = {"name": "Ana", "age": 20}
This is different from a list. A list uses positions like 0, 1, and 2. A dictionary uses keys like "name" and "age".
When to use a dictionary #
Use a dictionary when values need names instead of positions.
Common examples:
- A student record
- App settings
- Word counters
- Product details
- Grouped data
Example:
settings = {
"theme": "dark",
"language": "English",
"notifications": True
}
A dictionary is often a better choice than a list when you want fast lookup by key.
How to create a dictionary #
You can create a dictionary with curly braces {}.
student = {"name": "Ana", "age": 20}
print(student)
Output:
{'name': 'Ana', 'age': 20}
Empty dictionary #
data = {}
print(data)
Output:
{}
Using dict() #
You can also create a dictionary with dict():
student = dict(name="Ana", age=20)
print(student)
Output:
{'name': 'Ana', 'age': 20}
If you want more ways to create one, see creating a dictionary in Python.
How to access dictionary values #
Use square brackets with a key:
student = {"name": "Ana", "age": 20}
print(student["name"])
Output:
Ana
Using get() #
If a key might not exist, use get().
student = {"name": "Ana", "age": 20}
print(student.get("name"))
print(student.get("city"))
Output:
Ana
None
This is safer than using square brackets when the key may be missing.
student = {"name": "Ana"}
# print(student["city"]) # This would raise an error
print(student.get("city"))
To learn more, see the Python dictionary get() method or how to access values in a dictionary in Python.
How to add and change items #
To add a new item, assign a value to a new key.
student = {"name": "Ana", "age": 20}
student["city"] = "Paris"
print(student)
Output:
{'name': 'Ana', 'age': 20, 'city': 'Paris'}
To change an existing item, assign a new value to an existing key.
student = {"name": "Ana", "age": 20}
student["age"] = 21
print(student)
Output:
{'name': 'Ana', 'age': 21}
You can also change multiple items with the update() method.
How to remove items #
Use pop() to remove a key and get its value back.
student = {"name": "Ana", "age": 20, "city": "Paris"}
removed_value = student.pop("city")
print(removed_value)
print(student)
Output:
Paris
{'name': 'Ana', 'age': 20}
Use del to remove a key without returning its value.
student = {"name": "Ana", "age": 20}
del student["age"]
print(student)
Output:
{'name': 'Ana'}
Use clear() to remove everything.
student = {"name": "Ana", "age": 20}
student.clear()
print(student)
Output:
{}
Be careful: removing a missing key can raise an error.
student = {"name": "Ana"}
# del student["age"] # This would raise an error
For step-by-step help, see how to remove a key from a dictionary in Python.
Looping through a dictionary #
You can loop through keys, values, or both.
Loop through keys #
student = {"name": "Ana", "age": 20, "city": "Madrid"}
for key in student:
print(key)
Loop through values #
student = {"name": "Ana", "age": 20, "city": "Madrid"}
for value in student.values():
print(value)
Loop through key-value pairs #
This is often the easiest option when you need both the key and the value.
student = {"name": "Ana", "age": 20, "city": "Madrid"}
for key, value in student.items():
print(key, value)
Possible output:
name Ana
age 20
city Madrid
You can learn more about items(), keys(), and values(), or see how to loop through a dictionary in Python.
Important dictionary rules #
Here are some important rules beginners should know:
- Keys must be unique
- Keys should be immutable
- Values can be any type
- Dictionaries are mutable
Keys must be unique #
If the same key appears more than once, the later value replaces the earlier one.
data = {"name": "Ana", "name": "Luis"}
print(data)
Output:
{'name': 'Luis'}
Keys should be immutable #
Good key types include:
- Strings
- Numbers
- Tuples
These work well because they do not change.
Values can be any type #
A dictionary value can be a string, number, list, or even another dictionary.
student = {
"name": "Ana",
"age": 20,
"grades": [90, 85, 88],
"address": {"city": "Madrid", "zip": "28001"}
}
print(student)
Dictionaries are mutable #
This means you can change them after creation.
student = {"name": "Ana"}
student["name"] = "Eva"
print(student)
Dictionary methods to learn next #
These methods are very useful:
get()for safe lookupkeys()to view all keysvalues()to view all valuesitems()to work with key-value pairsupdate()to merge or change multiple items
Example:
student = {"name": "Ana", "age": 20}
print(student.keys())
print(student.values())
print(student.items())
student.update({"age": 21, "city": "Madrid"})
print(student)
Output:
dict_keys(['name', 'age'])
dict_values(['name', 20])
dict_items([('name', 'Ana'), ('age', 20)])
{'name': 'Ana', 'age': 21, 'city': 'Madrid'}
Common beginner problems #
Here are some common mistakes when working with dictionaries.
Using a key that does not exist #
This causes a KeyError if you use square brackets.
student = {"name": "Ana"}
# print(student["age"]) # KeyError
print(student.get("age")) # Safer
If you are seeing this error, read KeyError in Python: causes and fixes.
Confusing dictionaries with lists #
A dictionary does not use list positions like 0 and 1.
student = {"name": "Ana", "age": 20}
# print(student[0]) # Wrong
print(student["name"]) # Correct
Trying to use duplicate keys #
Only the last value is kept.
data = {"color": "red", "color": "blue"}
print(data)
Output:
{'color': 'blue'}
Forgetting that keys are case-sensitive #
These are different keys:
data = {"Name": "Ana", "name": "Luis"}
print(data)
Output:
{'Name': 'Ana', 'name': 'Luis'}
Using brackets instead of get() when a key may be missing #
Use get() when you are not sure a key exists.
Useful debugging checks #
If your dictionary code is not working, these quick checks can help:
print(my_dict)
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
print(type(my_dict))
print('name' in my_dict)
These are useful for spotting:
- Misspelled keys
- Wrong data type
- Missing keys
- Unexpected dictionary contents
✍️ Try it yourself
Create a dictionary book = {"title": "Python 101", "year": 2020}. Add a new key "author" with the value "Ana", update "year" to 2021, then safely look up "price" with get() (which is missing).
Show answer
book = {"title": "Python 101", "year": 2020}
book["author"] = "Ana"
book["year"] = 2021
print(book)
print(book.get("price"))
Output:
{'title': 'Python 101', 'year': 2021, 'author': 'Ana'}
None
FAQ #
What is a Python dictionary? #
A dictionary is a mutable data type that stores values as key-value pairs.
How is a dictionary different from a list? #
A list uses positions called indexes. A dictionary uses keys like names or labels.
Can dictionary keys be duplicated? #
No. If the same key appears more than once, the later value replaces the earlier one.
Can dictionary values have different data types? #
Yes. One dictionary can store strings, numbers, lists, or other dictionaries as values.
How do I safely get a value from a dictionary? #
Use get(), because it does not raise an error when the key is missing.