Python for AI ML - Day 8: Dictionaries in Python
Welcome to Day 8 of your AI/ML journey! Today, we’ll dive deep into dictionaries, one of Python’s most powerful data structures. Dictionaries store data as key-value pairs, making them ideal for fast lookups, structured data, and real-world applications like JSON processing. By the end of this guide, you’ll master dictionary creation, manipulation, methods, and use cases.
What Are Dictionaries?
Unordered Collection: Items are stored without a fixed order (though Python 3.7+ preserves insertion order).
Mutable: You can modify, add, or remove items after creation.
Key-Value Pairs: Each item has a unique key (immutable: strings, numbers, tuples) and an associated value (any data type).
Optimized for Speed: Keys are hashed for O(1) average time complexity lookups.
Creating Dictionaries
1. Basic Syntax
Use curly braces {} with key: value pairs:
student = {
"name": "Alice",
"age": 25,
"courses": ["Math", "Physics"]
}2. Empty Dictionary
empty_dict = {}
# or
empty_dict = dict()3. Using the dict() Constructor
Convert lists of tuples or keyword arguments:
# From tuples
country_codes = dict([("USA", 1), ("India", 91)])
# From keyword arguments
config = dict(debug=True, max_connections=10)Accessing Values
1. Square Brackets []
Retrieve values using keys. Raises KeyError if the key is missing:
print(student["name"]) # Output: Alice
# print(student["grade"]) # KeyError: 'grade'2. get() Method
Safely retrieve values with an optional default:
print(student.get("age")) # Output: 25
print(student.get("grade", "N/A")) # Output: N/A (default if key missing)Adding/Updating Entries
1. Add a New Key-Value Pair
student["country"] = "Canada"2. Update an Existing Key
student["age"] = 263. Bulk Updates with update()
Merge another dictionary or list of tuples:
student.update({"country": "Canada", "gpa": 3.8})
# Or
student.update([("country", "Canada"), ("gpa", 3.8)])Removing Entries
1. del Keyword
Delete a specific key:
del student["courses"] # Removes "courses" key2. pop() Method
Remove a key and return its value:
age = student.pop("age") # Returns 253. popitem()
Remove and return the last inserted item (Python 3.7+):
key, value = student.popitem() # Removes ("gpa", 3.8)4. clear()
Empty the dictionary:
student.clear() # {}Dictionary Methods
Nested Dictionaries
Dictionaries can contain other dictionaries, lists, or objects:
employees = {
"emp1": {
"name": "Alice",
"role": "Engineer"
},
"emp2": {
"name": "Bob",
"role": "Manager"
}
}
print(employees["emp1"]["name"]) # Output: AliceDictionary Operations
1. Check Key Existence
if "name" in student:
print("Key exists!")2. Length
print(len(student)) # Output: 33. Merge Dictionaries (Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3}
merged = dict1 | dict2 # {"a":1, "b":2, "c":3}Dictionary Comprehensions
Create dictionaries dynamically:
squares = {x: x**2 for x in range(1, 6)}
# Output: {1:1, 2:4, 3:9, 4:16, 5:25}Use Cases
JSON Data: Represent API responses or configurations.
Caching: Store computed values for fast retrieval.
Counting: Track frequencies of items (e.g., word counts).
Practice Exercise
Create a nested dictionary for a library catalog with books (title, author, year).
Add a new book, update the year of an existing one, and remove a book using
pop().Use a dictionary comprehension to map numbers 1-10 to their square roots (round to 2 decimals).
Solution:
# 1. Create library catalog
library = {
"book1": {
"title": "Python Crash Course",
"author": "Eric Matthes",
"year": 2019
},
"book2": {
"title": "Deep Learning",
"author": "Ian Goodfellow",
"year": 2016
}
}
# 2. Add/update/remove
library["book3"] = {"title": "AI for Everyone", "author": "Andrew Ng", "year": 2021}
library["book1"]["year"] = 2023
library.pop("book2")
# 3. Square roots
import math
sqrt_dict = {x: round(math.sqrt(x), 2) for x in range(1, 11)}Key Takeaways
Dictionaries store key-value pairs for efficient data retrieval.
Use
get()to safely access values andupdate()for bulk changes.Nested dictionaries model complex, hierarchical data.
Methods like
keys(),values(), anditems()are essential for iteration.



