Introduction to Dictionaries in Python
Dictionaries are one of the most powerful and flexible data structures in Python. They allow you to store key-value pairs, making data more structured and accessible.
What is a Dictionary?
A dictionary is a collection of key-value pairs. Each key is unique and maps to a specific value.
Example:
person = {
"name": "Amina",
"age": 28,
"is_student": False
}
"name"
is a key and"Amina"
is its value."age"
is a key and28
is its value."is_student"
is a key andFalse
is its value.
Syntax
- Dictionaries are defined using curly braces
{}
. - Keys and values are separated by colons
:
. - Each key-value pair is separated by commas.
dictionary_name = {
key1: value1,
key2: value2
}
Types of Values
Values in a dictionary can be:
- Strings
- Numbers
- Booleans
- Lists
- Other dictionaries
- Even functions!
Why Use Dictionaries?
Dictionaries are perfect when:
- You want to store related information (like a user profile).
- You want to access data by names (like "email" or "username"), not just positions like in a list.
They are fast, efficient, and readable.
Think About It
Why might a dictionary be better than a list in some cases?
Because you can access data directly using names instead of numeric indexes. For example:
person["name"]
is more meaningful thanperson[0]
.
Quick Practice
Create your own dictionary with at least three key-value pairs:
book = {
"title": "Python Basics",
"author": "Lance",
"pages": 200
}
print(book["title"])
Exercise: Try It Yourself!
Create a dictionary for a product in a store. It should have the keys: "name"
, "price"
, and "stock"
. Then print out the name and price.