Python Dictionaries: Organizing Data with Key-Value Pairs
Lesson Overview
Learn Python dictionaries - a powerful data structure that stores information using key-value pairs, just like a real-world phone book or dictionary. Master creating, accessing, and modifying dictionary data with practical examples that make data organization intuitive and efficient.
Lesson Content
Understanding Dictionaries: Real-World Connection
Imagine you have student information scattered across different pages - names on one page, ages on another, and ID card numbers on yet another page - every time you need complete information about one student, you'd have to flip through multiple pages and match positions, which is cumbersome and error-prone, just like how storing data in separate lists makes access difficult and inefficient. Dictionaries solve this by keeping each student bio-da (name, age, ID) is organized together in one page with clear labels, making it instantly accessible and meaningful without the hassle of cross-referencing multiple lists/pages.
Another Analogy is that its like having a physical phone book. You look up someone's name (the key) to find their phone number (the value). Or think of a real dictionary where you look up a word (key) to find its meaning (value). Python dictionaries work exactly the same way! They store data in key-value pairs where:
- Key: The label you use to find information (like a name or word)
- Value: The actual information stored (like a phone number or definition)
Dictionary Creation Accessing Dictionary Data
Dictionaries are created using curly braces { } with key-value pairs separated by colons
To retrieve values from a dictionary, you can use square brackets [] with the key name for direct access, or use the get() method for safer access that won't crash your program if the key doesn't exist."
# Restaurant menu Creation
# dict_variable = { 'key1' : value1 , 'key2' : value2}
menu = {
"burger": 250,
"pizza": 400,
"pasta": 300,
"salad": 150,
"coffee": 80
}
# Accessing values using keys
print(f"Burger costs: ₹{menu['burger']}") # Output: Burger costs: ₹250
print(f"Pizza costs: ₹{menu['pizza']}") # Output: Pizza costs: ₹400
# Safe way using get() method
price = menu.get("ice_cream")
print(price) # Output: None (no error!)
coffee_price = menu.get("coffee")
print(coffee_price) # Output: 80Dictionary vs List: When to Use What
| Aspect | Lists | Dictionaries |
|---|---|---|
| Access Method | By index position (0, 1, 2...) | By key name |
| Ordering | Always ordered by position | Ordered by key(Python 3.7+) |
| Best For | Sequential data, collections | Labeled data, relationships |
| Example Use | Shopping list, test scores | Student record, phone book |
| Access Speed | Slower for large data | Very fast lookups |