๐Ÿ“–Dictionaries: CRUD, Iteration, MethodsLESSON

Dictionaries: CRUD, Iteration, Methods

A dictionary is Python's built-in hash map โ€” a collection of key-value pairs where each key is unique. Dicts are ordered (insertion order preserved since Python 3.7), mutable, and extremely fast for lookup, insertion, and deletion.

Creating Dictionaries

CRUD Operations

Read

Create / Update

Delete

Iterating Dictionaries

Dict Comprehensions

Dict comprehensions mirror list comprehensions but produce a dict:

Merging Dicts (Python 3.9+)

Python 3.9 introduced the merge (|) and update (|=) operators for dicts, making merge code much cleaner:

Useful Methods Summary

MethodWhat it does
d[key]Get value (KeyError if missing)
d.get(key, default)Safe get
d[key] = valSet / overwrite
del d[key]Delete (KeyError if missing)
d.pop(key, default)Remove and return value
d.popitem()Remove and return last pair
d.update(other)Merge in-place
d.setdefault(key, val)Set only if absent
d.copy()Shallow copy
d.keys()View of all keys
d.values()View of all values
d.items()View of all (key, val) pairs
d.clear()Remove all items
key in dMembership test O(1)

Key Rules to Remember

  • Keys must be hashable โ€” strings, numbers, tuples are fine; lists and dicts are not.
  • Values can be anything โ€” lists, other dicts, functions, objects.
  • .copy() is a shallow copy โ€” nested objects are still shared. Use copy.deepcopy() when nesting matters.
  • Dict views (.keys(), .values(), .items()) are live โ€” they reflect changes made to the dict after the view was created.

Knowledge Check

What is the difference between d['key'] and d.get('key') when the key does not exist?

Which method inserts a key with a default value ONLY if the key is not already present?

Given d = {'a': 1, 'b': 2}, what does {'a': 0} | d produce in Python 3.9+?