Python Learning Session-08: Dictionaries in Python – Key-Value Magic!
👋 Welcome Back!
We’ve explored lists, which are great for storing ordered collections. But what if you need to store data with labels? For example, a student’s name and their marks. Lists can do it, but it’s messy. Enter Dictionaries—Python’s way of storing data as key-value pairs.
✅ What is a Dictionary?
A dictionary is like a real-life dictionary: you look up a word (key) and get its meaning (value). In Python:
- Keys are unique
- Values can be anything (numbers, strings, lists, even another dictionary)
- Defined using curly braces
{}
Example:
Output:
{'name': 'Alice', 'age': 21, 'marks': 85}
✔ Why useful? Perfect for structured data like user profiles, product details, etc.
✅ Creating Dictionaries
✅ Accessing Values
Use the key:
✔ Pro Tip: If you use a key that doesn’t exist, Python throws an error. Use get() to avoid that:
✅ Adding & Updating Data
✅ Removing Data
- pop() → Remove by key
- clear() → Remove all items
✅ Looping Through Dictionaries
✔ Real-world example: Displaying user details in a profile page.
✅ Dictionary Methods You’ll Love
keys()→ All keysvalues()→ All valuesitems()→ All key-value pairs
Example:
✅ Nested Dictionaries
Dictionaries inside dictionaries:
✔ Why powerful? Great for storing complex data like JSON.
✅ Summary
Dictionaries are the backbone of Python data handling. They’re fast, flexible, and perfect for real-world applications like APIs, databases, and configurations.
🔥 Challenge for You
Create a dictionary of 5 countries and their capitals. Then:
- Print all keys and values
- Add a new country
- Remove one country
👉 Next Session: Session-09: Tuples in Python – Immutable Collections!
No comments:
Post a Comment