Dictionaries Basics
Learn to store and access data using key-value pairs
Dictionaries Basics
What is a Dictionary?
Think of a real dictionary. When you want to know what "Python" means, you look up the word (key) and read its meaning (value).
A dictionary in Python works the same way. Instead of using positions like lists, you use names (keys) to store and find values.
Why use dictionaries?
- Store related information together (name, age, email)
- Find data quickly using meaningful names instead of numbers
- Organize data in a clear, readable way
- Perfect for real-world data like user profiles, settings, or products
Creating a Dictionary
You create a dictionary using curly braces. Inside, you write key-value pairs separated by colons.
student = {"name": "John", "age": 20, "grade": "A"}
print(student)What happens: Python creates a dictionary with 3 pieces of information. "name" is a key, "John" is its value. "age" is a key, 20 is its value.
Structure explained:
- Curly braces {} hold the dictionary
- Keys are like labels (usually text in quotes)
- Colons : connect keys to their values
- Commas , separate each key-value pair
Accessing Values
Instead of using numbers like in lists, you use the key name to get a value.
student = {"name": "John", "age": 20, "grade": "A"}
print(student["name"])
print(student["age"])What this shows:
- student["name"] gives you "John"
- student["age"] gives you 20
Real-world comparison: In a list, you ask "What's at position 0?" In a dictionary, you ask "What's the name?" Much more natural.
Using get() Method
There's a safer way to get values using the get() method.
student = {"name": "John", "age": 20}
print(student.get("name"))
print(student.get("email"))What's the difference:
- If key doesn't exist, get() returns None (no error)
- Using brackets [] gives an error if key doesn't exist
Setting a default value:
email = student.get("email", "No email")
print(email)What happens: Since "email" doesn't exist, it returns "No email" instead of None.
Adding and Changing Values
Dictionaries are flexible. You can add new key-value pairs or change existing ones.
Adding New Items
student = {"name": "John", "age": 20}
student["email"] = "john@example.com"
print(student)What this does: Adds a new key "email" with value "john@example.com". Dictionary now has 3 items.
Changing Existing Values
student = {"name": "John", "age": 20}
student["age"] = 21
print(student)What happens: Changes age from 20 to 21. Same key, new value.
Removing Items
There are several ways to remove items from a dictionary.
Using del - Remove Specific Key
student = {"name": "John", "age": 20, "grade": "A"}
del student["grade"]
print(student)Result: "grade" is removed. Dictionary now has {"name": "John", "age": 20}.
Using pop() - Remove and Get Value
student = {"name": "John", "age": 20, "grade": "A"}
removed = student.pop("grade")
print(removed)
print(student)What this does:
- Removes "grade" from dictionary
- Returns "A" so you can use it
- Dictionary now has 2 items
Using clear() - Remove Everything
student = {"name": "John", "age": 20}
student.clear()
print(student)Result: Empty dictionary {}
Checking if Key Exists
Use the word "in" to check if a key exists in your dictionary.
student = {"name": "John", "age": 20}
print("name" in student)
print("email" in student)Shows:
- True (name exists)
- False (email doesn't exist)
Why this matters: Always check before accessing to avoid errors.
if "email" in student:
print(student["email"])
else:
print("No email found")Dictionary Length
Use len() to count how many key-value pairs exist.
student = {"name": "John", "age": 20, "grade": "A"}
print(len(student))Shows: 3
Getting All Keys and Values
Getting All Keys
student = {"name": "John", "age": 20, "grade": "A"}
keys = student.keys()
print(keys)Shows: dict_keys(['name', 'age', 'grade'])
Getting All Values
values = student.values()
print(values)Shows: dict_values(['John', 20, 'A'])
Getting Both Keys and Values
items = student.items()
print(items)Shows: dict_items([('name', 'John'), ('age', 20), ('grade', 'A')])
Looping Through Dictionaries
You can go through all keys, values, or both using loops.
Loop Through Keys
student = {"name": "John", "age": 20}
for key in student:
print(key)Shows: name age
Loop Through Values
for value in student.values():
print(value)Shows: John 20
Loop Through Both
for key, value in student.items():
print(key + ":", value)Shows: name: John age: 20
Practice Example
The scenario: You're building a product catalog system. Each product has a name, price, and stock quantity.
product = {
"name": "Laptop",
"price": 999,
"stock": 5,
"category": "Electronics"
}
print("Product:", product["name"])
print("Price: " + str(product["price"]))
print("In stock:", product["stock"])
product["stock"] = product["stock"] - 1
print("After sale, stock:", product["stock"])
product["discount"] = 10
print("Discount added:", product["discount"] + " percent")
if "warranty" in product:
print("Warranty:", product["warranty"])
else:
print("No warranty information")
print("Total product details:", len(product))What this program does:
- Creates a product dictionary with 4 properties
- Displays product name, price, and stock
- Reduces stock by 1 after a sale
- Adds a new discount key
- Checks if warranty exists (it doesn't)
- Counts total number of properties
Key Points to Remember
Dictionaries store data in key-value pairs using curly braces. Keys are like labels, values are the data.
Access values using keys in square brackets or the get() method. get() is safer because it won't error if key doesn't exist.
You can add new items or change existing ones by assigning to a key. If key exists, value updates. If not, new pair is created.
Use "in" to check if a key exists before accessing it. This prevents errors in your program.
keys(), values(), and items() methods let you see all keys, all values, or both together.
Common Mistakes
Mistake 1: Using numbers as position
student = {"name": "John", "age": 20}
print(student[0]) # Error! Use key names, not positions
print(student["name"]) # Correct!Mistake 2: Accessing non-existent key
student = {"name": "John"}
print(student["age"]) # Error! Key doesn't exist
print(student.get("age")) # Returns None, no errorMistake 3: Forgetting quotes around string keys
student = {name: "John"} # Error! name needs quotes
student = {"name": "John"} # Correct!What's Next?
You now know dictionary basics. Next, you'll learn advanced dictionary operations like updating multiple items, copying dictionaries, nesting dictionaries, and more powerful techniques.