🐍

Dictionary Methods and Operations

Programare Python Intermediate 5 min read

Dictionary Methods and Operations

View Methods

  • keys() - Returns view of keys
  • values() - Returns view of values
  • items() - Returns view of (key, value) pairs

Modification Methods

  • update(other) - Merge dictionaries
  • setdefault(key, default) - Get or set default

Removal Methods

  • pop(key) - Remove and return
  • popitem() - Remove last pair
  • clear() - Remove all

Dict Comprehension

squares = {x: x**2 for x in range(5)}
inverted = {v: k for k, v in d.items()}

Copying

  • d.copy() or dict(d) - Shallow copy
  • copy.deepcopy(d) - Deep copy

Merging (Python 3.9+)

combined = d1 | d2
d1 |= d2  # In-place

Key Points

  • update() merges dictionaries
  • setdefault() gets or sets default value
  • copy() makes shallow copy
  • Never use mutable default with fromkeys()

📚 Related Articles