Dictionary Operations
Complete reference for Python dictionary methods and operations. Dictionaries are mutable, unordered collections of key-value pairs that provide fast lookup and flexible data storage capabilities.
Dictionary Creation and Basic Operations
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Empty Dictionary | {} or dict() | my_dict = {} | {} | Create empty dictionary |
Dictionary Literal | {key: value, ...} | {'a': 1, 'b': 2} | {'a': 1, 'b': 2} | Create with key-value pairs |
Dict Constructor | dict(key=value, ...) | dict(a=1, b=2) | {'a': 1, 'b': 2} | Create using constructor |
From Sequences | dict(sequence) | dict([('a', 1), ('b', 2)]) | {'a': 1, 'b': 2} | Create from key-value pairs |
Dictionary Comprehension | {k: v for k, v in iterable} | {x: x**2 for x in range(3)} | {0: 0, 1: 1, 2: 4} | Create with expression |
Length | len(dict) | len({'a': 1, 'b': 2}) | 2 | Get number of key-value pairs |
Membership | key in dict | 'a' in {'a': 1, 'b': 2} | True | Check if key exists |
Access Value | dict[key] | {'a': 1, 'b': 2}['a'] | 1 | Get value by key |
Set Value | dict[key] = value | d['a'] = 1 | Modifies dict | Set key-value pair |
Delete Item | del dict[key] | del d['a'] | Modifies dict | Remove key-value pair |
Accessing Dictionary Values
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
get() | Safe value access | d.get('key', 'default') | Value or default | Get value with optional default |
setdefault() | Get or set default | d.setdefault('key', 'default') | Value | Get value, set default if key missing |
Direct access | d['key'] | Value | Get value, raises KeyError if missing |
Adding and Updating Dictionary Items
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
update() | Update with dict/pairs | d.update({'key': 'value'}) | Modifies dict | Add/update multiple items |
key = value | Set single item | d['key'] = 'value' | Modifies dict | Add or update single item |
setdefault() | Set if missing | d.setdefault('key', 'default') | Value | Set only if key doesn't exist |
Removing Dictionary Items
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
pop() | Remove and return value | d.pop('key', default) | Value | Remove key, return value |
popitem() | Remove arbitrary item | d.popitem() | (key, value) tuple | Remove and return arbitrary pair |
clear() | Remove all items | d.clear() | {} | Empty the dictionary |
del | Delete key | del d['key'] | Modifies dict | Remove key-value pair |
Dictionary Views and Iteration
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
keys() | Get all keys | d.keys() | dict_keys view | View of dictionary keys |
values() | Get all values | d.values() | dict_values view | View of dictionary values |
items() | Get key-value pairs | d.items() | dict_items view | View of key-value pairs |
Dictionary Copying
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
copy() | Shallow copy | new_dict = d.copy() | New dict | Creates shallow copy |
dict() | Copy constructor | new_dict = dict(d) | New dict | Creates shallow copy |
**{dict} | Dictionary unpacking | new_dict = {**d} | New dict | Creates shallow copy (Python 3.5+) |
Advanced Dictionary Operations
Dictionary Comprehensions
Type | Syntax | Example | Result | Description |
---|---|---|---|---|
Basic | {k: v for k, v in iterable} | {x: x**2 for x in range(3)} | {0: 0, 1: 1, 2: 4} | Create dict from expression |
With Condition | {k: v for k, v in items if condition} | {k: v for k, v in d.items() if v > 0} | Filtered dict | Filter based on condition |
Key Transformation | {f(k): v for k, v in items} | {k.upper(): v for k, v in d.items()} | Modified keys | Transform keys |
Value Transformation | {k: f(v) for k, v in items} | {k: v*2 for k, v in d.items()} | Modified values | Transform values |
Performance Considerations
Time Complexity
Operation | Average Case | Worst Case | Notes |
---|---|---|---|
Access/Set/Delete | O(1) | O(n) | Hash collision can cause O(n) |
Search (in) | O(1) | O(n) | Checking key existence |
Iteration | O(n) | O(n) | Must visit all items |
Copy | O(n) | O(n) | Must copy all items |
Memory Considerations
# Dictionary memory usage
import sys
# Small dictionary
small_dict = {'a': 1, 'b': 2, 'c': 3}
print(sys.getsizeof(small_dict)) # Memory usage in bytes
# Dictionaries have some overhead
# Consider alternatives for simple cases:
# For fixed keys, consider namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(1, 2) # More memory efficient than {'x': 1, 'y': 2}
# For many similar dictionaries, consider __slots__
class Person:
__slots__ = ['name', 'age'] # Reduces memory usage
def __init__(self, name, age):
self.name = name
self.age = age
Best Practices
- Use get() for safe access: Prefer
dict.get(key, default)
over direct access when key might not exist - Check membership before access: Use
if key in dict:
before accessing unknown keys - Use dict comprehensions: More readable and often faster than loops
- Choose appropriate defaults: Use defaultdict for counters and grouping
- Be careful with mutable values: Remember that dictionary values can be mutable objects
- Use Counter for frequency counting: More convenient than manual counting
- Consider memory usage: Large dictionaries consume significant memory
- Use appropriate key types: Keys must be hashable (immutable types)
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.