Introduction
Python dictionaries are unordered, mutable collections of key-value pairs. They provide O(1) average-case lookup time, making them ideal for fast data retrieval. Dictionaries are extensively used in data science for representing JSON data, counting occurrences, and creating lookup tables.
Key Concepts
- Key-value pairs: Each item has a unique key mapped to a value
- Hashable keys: Keys must be immutable types (strings, numbers, tuples)
- Fast lookup: Dictionary operations are highly optimized
- Dynamic updates: Add, modify, or remove key-value pairs easily
- Dictionary comprehension: Create dictionaries from iterables
- Nested dictionaries: Dictionaries containing other dictionaries
Python Implementation
# Creating dictionaries
student = {"name": "John", "age": 25, "grade": "A"}
empty_dict = {}
dict_from_tuples = dict([("a", 1), ("b", 2)])
# Accessing values
name = student["name"] # Direct access
age = student.get("age", 0) # Safe access with default
keys = student.keys() # Get all keys
values = student.values() # Get all values
items = student.items() # Get all key-value pairs
# Modifying dictionaries
student["age"] = 26 # Update existing key
student["city"] = "New York" # Add new key-value pair
student.update({"grade": "A+", "id": 123}) # Batch update
# Dictionary comprehension
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
words = ["apple", "banana", "cherry"]
lengths = {word: len(word) for word in words}
# Iteration
for key in student:
print(key, student[key])
for k, v in student.items():
print(f"{k}: {v}")
When to Use
- Storing configuration settings
- Counting frequencies of elements
- Creating lookup tables for fast access
- Representing JSON and API responses
- Caching computed results
- Grouping data by a specific attribute
Key Takeaways
- Dictionaries provide constant-time lookup, making them efficient for large datasets
- Keys must be hashable, ensuring unique identification of values
- Dictionary comprehensions offer a concise way to create mappings
- The .get() method prevents KeyError when accessing non-existent keys
- Nested dictionaries can represent complex hierarchical data structures