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

OperationSyntaxExampleResultDescription
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 Constructordict(key=value, ...)dict(a=1, b=2){'a': 1, 'b': 2}Create using constructor
From Sequencesdict(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
Lengthlen(dict)len({'a': 1, 'b': 2})2Get number of key-value pairs
Membershipkey in dict'a' in {'a': 1, 'b': 2}TrueCheck if key exists
Access Valuedict[key]{'a': 1, 'b': 2}['a']1Get value by key
Set Valuedict[key] = valued['a'] = 1Modifies dictSet key-value pair
Delete Itemdel dict[key]del d['a']Modifies dictRemove key-value pair

Accessing Dictionary Values

MethodPurposeExampleResultDescription
get()Safe value accessd.get('key', 'default')Value or defaultGet value with optional default
setdefault()Get or set defaultd.setdefault('key', 'default')ValueGet value, set default if key missing
Direct accessd['key']ValueGet value, raises KeyError if missing

Adding and Updating Dictionary Items

MethodPurposeExampleResultDescription
update()Update with dict/pairsd.update({'key': 'value'})Modifies dictAdd/update multiple items
key = valueSet single itemd['key'] = 'value'Modifies dictAdd or update single item
setdefault()Set if missingd.setdefault('key', 'default')ValueSet only if key doesn't exist

Removing Dictionary Items

MethodPurposeExampleResultDescription
pop()Remove and return valued.pop('key', default)ValueRemove key, return value
popitem()Remove arbitrary itemd.popitem()(key, value) tupleRemove and return arbitrary pair
clear()Remove all itemsd.clear(){}Empty the dictionary
delDelete keydel d['key']Modifies dictRemove key-value pair

Dictionary Views and Iteration

MethodPurposeExampleResultDescription
keys()Get all keysd.keys()dict_keys viewView of dictionary keys
values()Get all valuesd.values()dict_values viewView of dictionary values
items()Get key-value pairsd.items()dict_items viewView of key-value pairs

Dictionary Copying

MethodPurposeExampleResultDescription
copy()Shallow copynew_dict = d.copy()New dictCreates shallow copy
dict()Copy constructornew_dict = dict(d)New dictCreates shallow copy
**{dict}Dictionary unpackingnew_dict = {**d}New dictCreates shallow copy (Python 3.5+)

Advanced Dictionary Operations

Dictionary Comprehensions

TypeSyntaxExampleResultDescription
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 dictFilter based on condition
Key Transformation{f(k): v for k, v in items}{k.upper(): v for k, v in d.items()}Modified keysTransform keys
Value Transformation{k: f(v) for k, v in items}{k: v*2 for k, v in d.items()}Modified valuesTransform values

Performance Considerations

Time Complexity

OperationAverage CaseWorst CaseNotes
Access/Set/DeleteO(1)O(n)Hash collision can cause O(n)
Search (in)O(1)O(n)Checking key existence
IterationO(n)O(n)Must visit all items
CopyO(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?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent