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:
Python
student = {
"name": "Alice",
"age": 21,
"marks": 85
}
print(student)
Show more lines
Output:
{'name': 'Alice', 'age': 21, 'marks': 85}
✔ Why useful? Perfect
for structured data like user profiles, product details, etc.
✅ Creating Dictionaries
Python
# Empty dictionary
my_dict = {}
# Dictionary with data
Show more lines
✅ Accessing Values
Use the key:
Python
print(student["name"]) # Alice
Show more lines
✔ Pro Tip: If
you use a key that doesn’t exist, Python throws an error. Use get() to
avoid that:
Python
print(student.get("grade", "Not
Available"))
Show more lines
✅ Adding & Updating Data
Python
student["grade"] = "A" #
Add new key-value
student["marks"] = 90 # Update
existing value
Show more lines
✅ Removing Data
- pop() →
Remove by key
Python
student.pop("age")
Show more lines
- clear() →
Remove all items
Python
student.clear()
Show more lines
✅ Looping Through
Dictionaries
Python
for key, value in student.items():
print(key, ":", value)
Show more lines
✔ Real-world example: Displaying
user details in a profile page.
✅ Dictionary Methods You’ll
Love
- keys() →
All keys
- values() →
All values
- items() →
All key-value pairs
Example:
Python
print(student.keys())
print(student.values())
Show more lines
✅ Nested Dictionaries
Dictionaries inside dictionaries:
Python
students = {
"101": {"name": "Alice", "marks": 85},
"102": {"name": "Bob", "marks": 78}
}
print(students["101"]["name"]) #
Alice
Show more lines
✔ 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