Introduction
Dictionaries store data in key-value pairs. They provide fast lookup using keys.
Creating Dictionaries
# Basic dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# From keys
keys = ["a", "b", "c"]
dict.fromkeys(keys, 0)
# Dict comprehension
squares = {x: x**2 for x in range(5)}
Dictionary Operations
person = {"name": "John", "age": 30}
# Accessing
print(person["name"]) # John
print(person.get("country", "USA")) # USA (default)
# Adding/updating
person["email"] = "john@email.com"
person.update({"country": "USA"})
# Removing
del person["age"]
email = person.pop("email")
# Methods
print(person.keys())
print(person.values())
print(person.items())
Practice Problems
- Count word frequency in text
- Merge two dictionaries
- Invert dictionary (swap keys and values)
- Group items by category
- Implement phonebook using dictionary