What You Will Learn
Beginner
- How to create and access dictionaries
- Adding, updating, and deleting keys
- Iterating over dictionaries
Terminalpython
# Creating dictionaries
person = {
"name": "Anita",
"age": 28,
"city": "Mumbai"
}
# Accessing (by key)
print(person["name"]) # Anita
print(person.get("age")) # 28
# .get() returns None (or default) if key not found
print(person.get("email")) # None
print(person.get("email", "N/A")) # N/AAdding, Updating, and Deleting
Terminalpython
person = {"name": "Anita", "age": 28}
# Add new key
person["email"] = "anita@example.com"
# Update existing
person["age"] = 29
# Delete
del person["email"]
popped = person.pop("age") # Remove and return value
print(person) # {'name': 'Anita'}
print(popped) # 29Iterating Over Dictionaries
Terminalpython
person = {"name": "Anita", "age": 28, "city": "Mumbai"}
# Keys only
for key in person.keys():
print(key)
# Values only
for value in person.values():
print(value)
# Both (most common)
for key, value in person.items():
print(f"{key}: {value}")KeyError
Accessing a non-existent key with [] raises KeyError. Use .get() to avoid errors: person.get("missing", "default").Practical Exercise
Create a dict: {"name": "Anita", "age": 28, "city": "Mumbai"}
Access: print(person["name"])
Add: person["email"] = "anita@example.com"
Loop with .items(): for k, v in person.items()
Use .get() for a missing key
Key Takeaways
- Dictionaries store key-value pairs.
- Access with dict[key] or safer dict.get(key, default).
- Add/update: dict[key] = value. Delete: del dict[key].
- Iterate: .keys(), .values(), .items().
- Keys must be immutable (str, int, tuple - not list).
Comments
Comments
Post a Comment