07
Day 7: Dictionaries
Chapter 7 • Beginner
35 min
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and does not allow duplicates.
What are Dictionaries?
Dictionaries in Python are like real-world dictionaries. You look up a word (key) to find its meaning (value). In programming, you use keys to find values.
Dictionary Properties:
- Ordered (as of Python 3.7)
- Changeable (can add, remove, modify items)
- No duplicate keys
- Indexed by keys (not by position)
Dictionary Methods:
- get() - Get value by key
- keys() - Get all keys
- values() - Get all values
- items() - Get all key-value pairs
- update() - Update dictionary
- pop() - Remove item by key
- clear() - Remove all items
- copy() - Copy dictionary
Hands-on Examples
Dictionary Operations
# Create dictionary
person = {
"name": "Elena",
"age": 30,
"city": "San Francisco",
"skills": ["Python", "JavaScript", "SQL"]
}
print("Person:", person)
print("Name:", person["name"])
print("Age:", person.get("age"))
# Add new key-value pair
person["email"] = "[email protected]"
print("After adding email:", person)
# Update existing value
person["age"] = 31
print("After updating age:", person)
# Dictionary methods
print("Keys:", list(person.keys()))
print("Values:", list(person.values()))
print("Items:", list(person.items()))
# Remove item
removed_skill = person["skills"].pop()
print("Removed skill:", removed_skill)
print("Updated skills:", person["skills"])Dictionaries are mutable and allow you to store key-value pairs efficiently.