Dictionaries store data as key-value pairs. They are useful when you need to look up values quickly using a unique key instead of an index.
What is a dictionary?
A dictionary is created with curly braces {}. Each item is a pair: a key followed by a colon : and a value. Pairs are separated by commas.
person = {
"name": "Alex",
"age": 25,
"city": "Berlin"
}
settings = {
"theme": "dark",
"notifications": True,
"volume": 75
}
You can also create an empty dictionary:
empty_dict = {}
Keys are usually strings or numbers. Values can be any type.
Accessing values with keys
Use square brackets [] and the key to get a value.
print(person["name"]) # Alex
print(person["age"]) # 25
Modifying and adding items
Dictionaries are mutable. Change a value with its key:
person["age"] = 26
print(person["age"]) # 26
Add a new key-value pair the same way:
person["job"] = "Developer"
print(person["job"]) # Developer
Key differences: list vs dictionary
- A list uses numeric indexes (0, 1, 2...) to access items in order.
- A dictionary uses custom keys (often strings) to access values directly.
Example comparison:
# List: access by position
fruits_list = ["apple", "banana", "cherry"]
print(fruits_list[1]) # banana
# Dictionary: access by key
fruits_dict = {
"first": "apple",
"second": "banana",
"third": "cherry"
}
print(fruits_dict["second"]) # banana
Dictionaries are faster for lookups when keys are meaningful.
Common examples
Simple translation dictionary:
translate = {
"hello": "hallo",
"goodbye": "auf Wiedersehen",
"thanks": "danke"
}
print(translate["hello"]) # hallo
translate["yes"] = "ja"
User information:
user = {
"username": "alex123",
"email": "alex@example.com",
"active": True
}
print(user["email"]) # alex@example.com
Common mistake: KeyError
If you try to access a key that does not exist, Python raises an error.
print(person["phone"]) # KeyError: 'phone'
Check if a key exists first, or use .get() which returns None if missing:
print(person.get("phone")) # None
Quick summary
- Create dictionaries with curly braces and key-value pairs.
- Access and modify values using keys in square brackets.
- Add new items by assigning to a new key.
- Keys must be unique; use meaningful names.
- Dictionaries are key-based, unlike order-based lists.
Practice building small dictionaries for real data. They are essential for organizing information in Python programs.
Top comments (0)