Python Dictionary Methods Cheat Sheet
Quick-reference for every dict method and pattern you actually use. Each section includes copy-ready snippets with inline output comments.
Creating Dictionaries
Multiple ways to create dicts: literal syntax, dict() constructor, zip, and comprehensions.
d = {'name': 'Alice', 'age': 30}
d['name'] # => 'Alice'd = dict(name='Alice', age=30)
d # => {'name': 'Alice', 'age': 30}keys = ['a', 'b', 'c']
vals = [1, 2, 3]
dict(zip(keys, vals)) # => {'a': 1, 'b': 2, 'c': 3}{x: x**2 for x in range(5)}
# => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}dict.fromkeys(['a', 'b', 'c'], 0)
# => {'a': 0, 'b': 0, 'c': 0}All keys share the same default object. Avoid mutable defaults like [].
Accessing Values: get, setdefault, pop
d[key] raises KeyError on miss. get() and setdefault() provide safe alternatives.
d = {'a': 1, 'b': 2}
d['a'] # => 1
d.get('c') # => None (no KeyError)
d.get('c', 0) # => 0 (custom default)d = {'a': 1}
d.setdefault('a', 99) # => 1 (key exists, no change)
d.setdefault('b', 99) # => 99 (key missing, inserted)
d # => {'a': 1, 'b': 99}d = {'a': 1, 'b': 2, 'c': 3}
d.pop('b') # => 2 (removes 'b')
d.pop('z', None) # => None (missing key, no error)
d # => {'a': 1, 'c': 3}d = {'a': 1, 'b': 2, 'c': 3}
d.popitem() # => ('c', 3)
d # => {'a': 1, 'b': 2}popitem() raises KeyError on an empty dict. Useful for consuming entries one by one.
Iterating: keys, values, items
Three views into a dictionary: keys(), values(), and items() for key-value pairs.
d = {'a': 1, 'b': 2}
for k in d:
print(k) # => 'a', 'b'for v in d.values():
print(v) # => 1, 2for k, v in d.items():
print(f'{k}={v}') # => 'a=1', 'b=2'for i, (k, v) in enumerate(d.items()):
print(f'{i}: {k}={v}') # => '0: a=1', '1: b=2'Updating and Merging Dicts
Combine dictionaries with update(), the | merge operator (3.9+), or unpacking.
d = {'a': 1, 'b': 2}
d.update({'b': 20, 'c': 3})
d # => {'a': 1, 'b': 20, 'c': 3}defaults = {'color': 'blue', 'size': 'M'}
overrides = {'size': 'L', 'brand': 'Acme'}
merged = defaults | overrides
merged # => {'color': 'blue', 'size': 'L', 'brand': 'Acme'}The right-hand dict wins on key conflicts. The original dicts are unchanged.
d = {'a': 1}
d |= {'b': 2, 'c': 3}
d # => {'a': 1, 'b': 2, 'c': 3}merged = {**defaults, **overrides}
# Same as defaults | overridesDict Comprehensions
prices = {'apple': 1.00, 'banana': 0.50}
{k: v * 1.1 for k, v in prices.items()}
# => {'apple': 1.1, 'banana': 0.55}scores = {'Alice': 85, 'Bob': 42, 'Carol': 91}
{k: v for k, v in scores.items() if v >= 70}
# => {'Alice': 85, 'Carol': 91}d = {'a': 1, 'b': 2}
{v: k for k, v in d.items()} # => {1: 'a', 2: 'b'}items = ['apple', 'banana', 'cherry']
{i: item for i, item in enumerate(items)}
# => {0: 'apple', 1: 'banana', 2: 'cherry'}Specialized Dicts: Counter, defaultdict, OrderedDict
The collections module provides dict subclasses for common patterns like counting and grouping.
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
c = Counter(words)
c # => Counter({'apple': 3, 'banana': 2, 'cherry': 1})
c.most_common(2) # => [('apple', 3), ('banana', 2)]from collections import Counter
a = Counter('aabbc')
b = Counter('abbcc')
a + b # => Counter({'b': 3, 'a': 3, 'c': 3})
a - b # => Counter({'a': 1})Subtraction drops zero and negative counts.
from collections import defaultdict
groups = defaultdict(list)
for name, dept in [('Alice', 'eng'), ('Bob', 'eng'), ('Carol', 'sales')]:
groups[dept].append(name)
dict(groups) # => {'eng': ['Alice', 'Bob'], 'sales': ['Carol']}from collections import defaultdict
counts = defaultdict(int)
for word in ['a', 'b', 'a', 'c', 'a']:
counts[word] += 1
dict(counts) # => {'a': 3, 'b': 1, 'c': 1}Nested Dictionaries
Dicts inside dicts model hierarchical data. Access carefully to avoid KeyError chains.
users = {
'alice': {'age': 30, 'city': 'NYC'},
'bob': {'age': 25, 'city': 'LA'},
}
users['alice']['city'] # => 'NYC'users.get('carol', {}).get('city', 'unknown')
# => 'unknown' (no KeyError even though carol is missing)users['alice']['age'] = 31
users['alice'] # => {'age': 31, 'city': 'NYC'}flat = {
f'{user}.{key}': val
for user, info in users.items()
for key, val in info.items()
}
# => {'alice.age': 31, 'alice.city': 'NYC', 'bob.age': 25, 'bob.city': 'LA'}Sorting Dictionaries
Dicts preserve insertion order (Python 3.7+). Sort by key or value with sorted().
d = {'banana': 3, 'apple': 1, 'cherry': 2}
dict(sorted(d.items()))
# => {'apple': 1, 'banana': 3, 'cherry': 2}dict(sorted(d.items(), key=lambda kv: kv[1]))
# => {'apple': 1, 'cherry': 2, 'banana': 3}dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))
# => {'banana': 3, 'cherry': 2, 'apple': 1}from collections import Counter
c = Counter('abracadabra')
c.most_common(3) # => [('a', 5), ('b', 2), ('r', 2)]Removing Entries
d = {'a': 1, 'b': 2, 'c': 3}
del d['b']
d # => {'a': 1, 'c': 3}Raises KeyError if key is missing. Check with "in" first or use pop().
d = {'a': 1}
d.pop('z', None) # => None (no KeyError)d = {'a': 1, 'b': 2}
d.clear()
d # => {}d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{k: v for k, v in d.items() if v > 2}
# => {'c': 3, 'd': 4}Membership and Comparison
d = {'a': 1, 'b': 2}
'a' in d # => True
'z' in d # => False
'z' not in d # => True{'a': 1, 'b': 2} == {'b': 2, 'a': 1} # => TrueOrder does not matter for equality. Both keys and values must match.
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'b': 20, 'c': 30, 'd': 4}
d1.keys() & d2.keys() # => {'b', 'c'} (intersection)
d1.keys() - d2.keys() # => {'a'} (difference)Can you write this from memory?
Create an empty list called items