How do I use dictionaries for key-value storage in Python?

· Category: Python Programming

Short answer

Python dictionaries store key-value pairs in a hash table. They are mutable, unordered historically, but insertion-ordered as of Python 3.7+. Use curly braces {} or the dict() constructor to create them.

Steps

  1. Create a dictionary: d = {"key": "value"}.
  2. Access values by key: d["key"] or d.get("key", default).
  3. Add or update entries: d["new_key"] = value.
  4. Iterate over keys, values, or items.
user = {"name": "Alice", "age": 30}
print(user["name"])
user["email"] = "[email protected]"

# Safe access
print(user.get("phone", "N/A"))

# Iteration
for key, value in user.items():
    print(f"{key}: {value}")

Tips

  • Use .setdefault() or collections.defaultdict to handle missing keys gracefully.
  • Dictionary comprehensions are concise: {k: v for k, v in pairs}.
  • Merge dictionaries with the | operator (Python 3.9+) or {**d1, **d2}.
  • Keys must be hashable (immutable types like strings, numbers, or tuples of hashables).
# Merge
d1 = {"a": 1}
d2 = {"b": 2}
merged = d1 | d2
print(merged)

# Comprehension
squares = {x: x**2 for x in range(6)}
print(squares)

Common issues

  • Accessing a missing key with d[key] raises a KeyError; prefer .get() when the key might be absent.
  • Using a mutable type (like a list) as a key raises a TypeError.
  • Iterating over a dictionary and modifying it simultaneously can raise a RuntimeError.