In Python, a dictionary is a powerful built-in data structure that allows you to store data as key-value pairs. It’s ideal for representing structured information like user profiles, configuration settings, or any data that maps one item to another.
Let’s dive into how dictionaries work and how you can use them effectively in your Python programs.
A dictionary is defined using curly braces {} with keys and values separated by colons :.
person = {
"name": "Ali",
"age": 30,
"city": "Lahore"
}
Each key must be unique and immutable (like strings, numbers, or tuples). Values can be of any data type.
You can access a value by referencing its key:
print(person["name"]) # Output: Ali
⚠️ If the key doesn’t exist, Python raises a KeyError.
To avoid errors, use .get():
print(person.get("email")) # Output: None
You can also provide a default value:
print(person.get("email", "Not Provided")) # Output: Not Provided
keys() - Returns all keys
values() - Returns all values
items() - Returns key-value pairs as tuples
update() - Adds or updates key-value pairs
pop(key) - Removes a key and returns its value
clear() - Removes all items
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.items()) # dict_items([('name', 'Ali'), ('age', 30), ('city', 'Lahore')])
You can loop through keys, values, or both:
for key in person:
print(key, person[key])
for key, value in person.items():
print(f"{key}: {value}")
Storing user data
Mapping IDs to names
Counting occurrences
Representing JSON-like structures
inventory = {
"apple": 10,
"banana": 5,
"orange": 8
}
Try this:
student = {
"name": "Zara",
"grades": [85, 90, 78]
}
# Access the second grade
print(student["grades"][1])
Dictionaries are one of the most versatile and efficient data structures in Python. They allow you to organize and retrieve data quickly using meaningful keys.
Next Up: Defining functions with def