Python Cheatsheet

Dictionaries

Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Creating Dictionaries

d = {}                            # empty
d = {"a": 1, "b": 2}
d = dict(a=1, b=2)                # keyword args (keys become strings)
d = dict([("a", 1), ("b", 2)])   # from iterable of pairs
d = dict(zip(keys, values))       # zip two lists
d = {k: v for k, v in pairs}     # dict comprehension
d = dict.fromkeys(["a", "b", "c"], 0)  # all values → 0

Accessing and Modifying

d = {"x": 10, "y": 20}

d["x"]              # 10  (KeyError if missing)
d.get("x")          # 10
d.get("z")          # None  (no KeyError)
d.get("z", 0)       # 0  (custom default)

d["z"] = 30         # add or update
d["x"] += 5         # update in place

del d["x"]          # remove key (KeyError if missing)
d.pop("x")          # remove and return value (KeyError if missing)
d.pop("x", None)    # remove and return, or None if missing
d.popitem()         # remove and return last inserted (k, v) pair (LIFO)
d.clear()           # remove all

Dictionary Methods

MethodReturnsDescription
d.keys()dict_keys viewAll keys
d.values()dict_values viewAll values
d.items()dict_items viewAll (key, value) pairs
d.get(k, default)value or defaultSafe lookup
d.setdefault(k, default)valueGet or insert default
d.update(other)NoneMerge another dict (or iterable of pairs)
d.pop(k, default)valueRemove and return
d.popitem()(k, v)Remove and return last pair
d.clear()NoneRemove all
d.copy()dictShallow copy
# setdefault — insert and return default if key missing
d.setdefault("count", 0)
d["count"] += 1

# Views are live (reflect changes to dict)
keys = d.keys()
d["new"] = 1
"new" in keys   # True

# Iterate items
for k, v in d.items():
    print(f"{k}: {v}")

Merging and Updating

a = {"x": 1}
b = {"y": 2, "x": 99}

# update() — modifies in place
a.update(b)              # a = {"x": 99, "y": 2}
a.update(z=3)            # keyword form

# Merge operator (Python 3.9+)
merged = a | b           # new dict; b's values win on collision
a |= b                   # in-place merge

# Unpacking (Python 3.5+)
merged = {**a, **b}      # b's values win on collision
merged = {**a, **b, "extra": 42}

Membership and Length

"key" in d          # True if key exists (O(1))
"key" not in d
len(d)              # number of key-value pairs

Default Dictionaries

from collections import defaultdict

# Auto-initializes missing keys
word_count = defaultdict(int)
for word in text.split():
    word_count[word] += 1

groups = defaultdict(list)
for item in data:
    groups[item.category].append(item)

# defaultdict(set), defaultdict(dict), defaultdict(lambda: "N/A")
nested = defaultdict(lambda: defaultdict(int))
nested["a"]["b"] += 1

Ordered Dictionary

Python 3.7+ dict preserves insertion order. OrderedDict adds extra features:

from collections import OrderedDict

od = OrderedDict()
od["a"] = 1
od["b"] = 2
od.move_to_end("a")          # move "a" to end
od.move_to_end("b", last=False)  # move "b" to front
od.popitem(last=True)        # remove last (LIFO)
od.popitem(last=False)       # remove first (FIFO)

# OrderedDict equality considers order; dict equality does not
OrderedDict([("a", 1), ("b", 2)]) == OrderedDict([("b", 2), ("a", 1)])  # False
{"a": 1, "b": 2} == {"b": 2, "a": 1}  # True

Counter

from collections import Counter

c = Counter("abracadabra")        # {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
c = Counter(["a", "b", "a"])     # Counter({'a': 2, 'b': 1})
c = Counter({"a": 3, "b": 1})

c["a"]          # 5
c["z"]          # 0  (no KeyError for missing)
c.most_common(3)      # [('a', 5), ('b', 2), ('r', 2)]
c.most_common()[:-4:-1]  # 3 least common
c.elements()          # iterator over elements (with repetition)
list(c.elements())    # ['a', 'a', 'a', 'a', 'a', 'b', 'b', ...]

# Arithmetic
c1 = Counter(a=3, b=2)
c2 = Counter(a=1, b=4)
c1 + c2   # Counter({'b': 6, 'a': 4})
c1 - c2   # Counter({'a': 2})  (non-positive removed)
c1 & c2   # Counter({'a': 1, 'b': 2})  (min)
c1 | c2   # Counter({'b': 4, 'a': 3})  (max)

# Update
c.update(["a", "a", "b"])   # add counts
c.subtract(["a", "b"])      # subtract counts (can go negative)

Sorting Dictionaries

# Sort by key
dict(sorted(d.items()))
{k: d[k] for k in sorted(d)}

# Sort by value
dict(sorted(d.items(), key=lambda kv: kv[1]))
dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))

# Get key with max value
max(d, key=d.get)
min(d, key=d.get)

Nested Dictionaries

nested = {
    "alice": {"age": 30, "city": "NYC"},
    "bob":   {"age": 25, "city": "LA"},
}

nested["alice"]["age"]          # 30
nested.get("charlie", {}).get("age", "unknown")  # safe deep access

# Deep get helper
def deep_get(d, *keys, default=None):
    for k in keys:
        if not isinstance(d, dict):
            return default
        d = d.get(k, default)
    return d

deep_get(nested, "alice", "age")   # 30
deep_get(nested, "x", "y")         # None

Dictionary Comprehension

# Basic
{k: v for k, v in pairs}
{k: k**2 for k in range(5)}        # {0:0, 1:1, 2:4, 3:9, 4:16}

# Filter
{k: v for k, v in d.items() if v > 0}

# Invert a dict (assumes unique values)
inv = {v: k for k, v in d.items()}

# Transform values
upper = {k: v.upper() for k, v in d.items()}

ChainMap

Logical layering of dicts (read searches all; write goes to first).

from collections import ChainMap

defaults = {"color": "red", "size": "M"}
user_prefs = {"color": "blue"}

settings = ChainMap(user_prefs, defaults)
settings["color"]   # "blue"  (from user_prefs)
settings["size"]    # "M"     (from defaults)

settings["font"] = "mono"   # writes to user_prefs only