Welcome to Day 25 of the 100 Days of Python series!
Today, we’ll master one of the most powerful and flexible data structures in Python — the dictionary.
Dictionaries let you store key-value pairs, giving you lightning-fast lookups and structured data organization. If you’ve used JSON or dealt with APIs, you’ve already seen dictionaries in action.
Let’s dive in and master them. 🐍💼
📦 What You’ll Learn
- What dictionaries are and why they’re useful
- How to create and access key-value pairs
- Modifying, adding, and removing items
- Dictionary methods and looping
- Nested dictionaries and real-world use cases
🧠 What is a Dictionary?
A dictionary in Python is an unordered, mutable collection of key-value pairs.
🔹 Syntax
person = { "name": "Alice", "age": 30, "city": "New York" }
Keys are unique. Values can be any data type.
🔑 Creating a Dictionary
empty = {} user = dict(name="John", age=25)
🔍 Accessing Values by Key
print(person["name"]) # Alice
✅ Safe Access with get()
print(person.get("age")) # 30 print(person.get("email", "N/A")) # N/A
✏️ Modifying and Adding Items
person["age"] = 31 # Modify person["email"] = "a@b.com" # Add
❌ Removing Items
person.pop("age") # Removes by key del person["city"] # Another way person.clear() # Removes all
🔁 Looping Through a Dictionary
for key in person: print(key, person[key]) # Or, more readable: for key, value in person.items(): print(f"{key}: {value}")
🔄 Dictionary Methods
Method | Purpose |
---|---|
keys() | Returns all keys |
values() | Returns all values |
items() | Returns key-value pairs |
get(key) | Returns value or None/default |
pop(key) | Removes key and returns its value |
update(dict2) | Updates with another dictionary |
clear() | Clears all items |
🧱 Nested Dictionaries
Dictionaries can hold other dictionaries:
users = { "alice": {"age": 30, "city": "Paris"}, "bob": {"age": 25, "city": "Berlin"} } print(users["alice"]["city"]) # Paris
💡 Dictionary Comprehension
squares = {x: x*x for x in range(5)} print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
📊 Real-World Examples
1. Counting Frequency
text = "apple banana apple orange" counts = {} for word in text.split(): counts[word] = counts.get(word, 0) + 1 print(counts) # {'apple': 2, 'banana': 1, 'orange': 1}
2. Storing API Responses (e.g., JSON)
response = { "status": "success", "data": { "user": "Alice", "id": 123 } } print(response["data"]["user"]) # Alice
3. Mapping IDs to Data
products = { 101: "Shoes", 102: "Shirt", 103: "Bag" } print(products[102]) # Shirt
🚫 Common Mistakes
- ❌ Using mutable types like lists as keys
- ❌ Assuming order (dictionaries are ordered since Python 3.7, but don’t rely on it for logic)
- ✅ Use
.get()
when you're unsure if a key exists
🧠 Recap
Today you learned:
- How dictionaries store data using key-value pairs
- How to add, modify, delete, and access items
- Useful methods like
.get()
,.items()
,.update()
- How to nest dictionaries and write comprehensions
- Real-world applications like counters and JSON
Top comments (0)