Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. Python
  4. Python Dictionary Methods Cheat Sheet
PythonCheat Sheet

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.

On this page
  1. 1Creating Dictionaries
  2. 2Accessing Values: get, setdefault, pop
  3. 3Iterating: keys, values, items
  4. 4Updating and Merging Dicts
  5. 5Dict Comprehensions
  6. 6Specialized Dicts: Counter, defaultdict, OrderedDict
  7. 7Nested Dictionaries
  8. 8Sorting Dictionaries
  9. 9Removing Entries
  10. 10Membership and Comparison
Creating DictionariesAccessing Values: get, setdefault, popIterating: keys, values, itemsUpdating and Merging DictsDict ComprehensionsSpecialized Dicts: Counter, defaultdict, OrderedDictNested DictionariesSorting DictionariesRemoving EntriesMembership and Comparison

Creating Dictionaries

Multiple ways to create dicts: literal syntax, dict() constructor, zip, and comprehensions.

Literal syntax
d = {'name': 'Alice', 'age': 30}
d['name']   # => 'Alice'
dict() constructor
d = dict(name='Alice', age=30)
d   # => {'name': 'Alice', 'age': 30}
From pairs with zip()
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
dict(zip(keys, vals))   # => {'a': 1, 'b': 2, 'c': 3}
Dict comprehension
{x: x**2 for x in range(5)}
# => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
fromkeys() with default value
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[key] vs get()
d = {'a': 1, 'b': 2}
d['a']           # => 1
d.get('c')       # => None  (no KeyError)
d.get('c', 0)    # => 0     (custom default)
setdefault(): get or insert
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}
pop(): remove and return
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}
popitem(): remove last inserted
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.

Loop over keys (default)
d = {'a': 1, 'b': 2}
for k in d:
    print(k)   # => 'a', 'b'
Loop over values
for v in d.values():
    print(v)   # => 1, 2
Loop over key-value pairs
for k, v in d.items():
    print(f'{k}={v}')   # => 'a=1', 'b=2'
Enumerate items with index
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.

update() modifies in place
d = {'a': 1, 'b': 2}
d.update({'b': 20, 'c': 3})
d   # => {'a': 1, 'b': 20, 'c': 3}
Merge operator | (Python 3.9+)
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.

In-place merge |= (Python 3.9+)
d = {'a': 1}
d |= {'b': 2, 'c': 3}
d   # => {'a': 1, 'b': 2, 'c': 3}
Unpack merge (pre-3.9)
merged = {**defaults, **overrides}
# Same as defaults | overrides

Dict Comprehensions

Transform values
prices = {'apple': 1.00, 'banana': 0.50}
{k: v * 1.1 for k, v in prices.items()}
# => {'apple': 1.1, 'banana': 0.55}
Filter by value
scores = {'Alice': 85, 'Bob': 42, 'Carol': 91}
{k: v for k, v in scores.items() if v >= 70}
# => {'Alice': 85, 'Carol': 91}
Swap keys and values
d = {'a': 1, 'b': 2}
{v: k for k, v in d.items()}   # => {1: 'a', 2: 'b'}
From list with enumerate
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.

Counter: count occurrences
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)]
Counter arithmetic
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.

defaultdict: auto-create missing keys
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']}
defaultdict for counting
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.

Create and access nested dict
users = {
    'alice': {'age': 30, 'city': 'NYC'},
    'bob':   {'age': 25, 'city': 'LA'},
}
users['alice']['city']   # => 'NYC'
Safe nested access with get()
users.get('carol', {}).get('city', 'unknown')
# => 'unknown'  (no KeyError even though carol is missing)
Update nested value
users['alice']['age'] = 31
users['alice']   # => {'age': 31, 'city': 'NYC'}
Flatten nested dict
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().

Sort by key
d = {'banana': 3, 'apple': 1, 'cherry': 2}
dict(sorted(d.items()))
# => {'apple': 1, 'banana': 3, 'cherry': 2}
Sort by value (ascending)
dict(sorted(d.items(), key=lambda kv: kv[1]))
# => {'apple': 1, 'cherry': 2, 'banana': 3}
Sort by value (descending)
dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))
# => {'banana': 3, 'cherry': 2, 'apple': 1}
Top-N by value
from collections import Counter
c = Counter('abracadabra')
c.most_common(3)   # => [('a', 5), ('b', 2), ('r', 2)]

Removing Entries

del statement
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().

pop() with default
d = {'a': 1}
d.pop('z', None)   # => None  (no KeyError)
clear() removes all
d = {'a': 1, 'b': 2}
d.clear()
d   # => {}
Remove by comprehension
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

Check key existence
d = {'a': 1, 'b': 2}
'a' in d       # => True
'z' in d       # => False
'z' not in d   # => True
Dict equality
{'a': 1, 'b': 2} == {'b': 2, 'a': 1}   # => True

Order does not matter for equality. Both keys and values must match.

Set operations on keys
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)
Learn Python in Depth
Python Comprehensions Practice →Python Loops Practice →Python Strings Practice →
Warm-up1 / 2

Can you write this from memory?

Create an empty list called items

See Also
List Comprehensions →Loops →

Start Practicing Python

Free daily exercises with spaced repetition. No credit card required.

← Back to Python Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.