π Dictionaries in Python#
Dictionaries are one of the most powerful and versatile data types in Python. They allow you to store data in key-value pairs, making it super easy to organize and look up information. Letβs dive into how dictionaries work! π
What is a Dictionary? π#
A dictionary is a collection of key-value pairs enclosed in curly braces { }
. Each key points to a value.
student = {
"name": "Ravi",
"age": 21,
"city": "Mumbai"
}
- “name”, “age”, “city” are keys.
- “Ravi”, 21, and “Mumbai” are their corresponding values.
Creating Dictionaries βοΈ#
empty_dict = {}
person = {"first_name": "Asha", "last_name": "Sharma", "age": 25}
Accessing Values π#
Use the key inside square brackets or the .get()
method.
print(person["first_name"]) # Asha
print(person.get("age")) # 25
Adding & Modifying Items βοΈ#
Add or change a keyβs value by simple assignment:
person["age"] = 26 # Modify existing key
person["city"] = "Delhi" # Add new key-value pair
Removing Items β#
Several methods to remove:
del person["city"]
β deletes the key and valueperson.pop("age")
β removes key and returns valueperson.clear()
β empties the whole dictionary
Useful Dictionary Methods π οΈ#
Method | Description | Example |
---|---|---|
.keys() | Returns all keys | person.keys() |
.values() | Returns all values | person.values() |
.items() | Returns pairs (key, value) | person.items() |
.update() | Updates dictionary with another | person.update(new_info) |
Looping Through Dictionaries π#
Iterate through keys, values, or both:
for key in person:
print(key, ":", person[key])
# Or
for key, value in person.items():
print(key, "=>", value)
Practice Questions with Solutions π―#
- Practice: Create a dictionary for a book with keys
title
,author
, andyear
. Print the author.- Solution:
book = {"title": "Python 101", "author": "John Smith", "year": 2020}
print(book["author"]) # John Smith
- Practice: Update the year of the book to 2021.
- Solution:
book["year"] = 2021
- Practice: Remove the
year
key from the dictionary.- Solution:
del book["year"]
Step-by-Step Mini Project: Contact Book π#
Create a dictionary to store contact details like name, phone, and email, and print all details.
contact = {
"name": "Sita",
"phone": "9998887777",
"email": "sita@example.com"
}
for key, value in contact.items():
print(f"{key.title()}: {value}")
Output:
Name: Sita
Phone: 9998887777
Email: sita@example.com
Checklist for This Chapter β #
- Created and accessed dictionaries
- Added, modified, and removed items
- Used common dictionary methods
- Looped through keys and values effectively
You are now ready to organize data smartly with dictionariesβthink of them as your real-world data maps! Keep practicing by building address books, inventory systems, and more! π―