The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create a dictionaryuser = {"name": "Ada", "role": "engineer"}View examples
Create from keywordsuser = dict(name="Ada", role="engineer")View examples
Read a required keyname = user["name"]View examples
Read an optional keytimezone = user.get("timezone", "UTC")View examples
Check for a keyif "role" in user: print(user["role"])View examples
Set one valueuser["active"] = TrueView examples
Update several valuesuser.update({"role": "lead", "active": True})View examples
Create a merged dictionarycombined = defaults | overridesView examples
Remove and return a valuerole = user.pop("role", None)View examples
Delete a required keydel user["active"]View examples
Iterate over pairsfor key, value in user.items(): print(key, value)View examples
Iterate over keysfor key in user: print(key)View examples
Build with a comprehensionsquares = {number: number ** 2 for number in range(4)}View examples
Initialize a missing keytags = groups.setdefault("python", [])View examples

Dictionaries map unique, hashable keys to values. Choose direct indexing when a key must exist, use get for optional keys, and iterate through views when you need keys, values, or both.

Step by step

Detailed examples

01

Create dictionaries from values

A dictionary literal works with any hashable keys and makes the mapping visible. The dict constructor is concise when every key is a valid Python identifier and should become a string.

Literal and constructor forms
user = {"name": "Ada", "role": "engineer"}
settings = dict(theme="dark", compact=True)

print(user)
print(settings)
Output
{'name': 'Ada', 'role': 'engineer'}
{'theme': 'dark', 'compact': True}

Note: The keyword form cannot directly create keys containing spaces, hyphens, or other non-identifier characters.

Back to quick reference ↑
02

Choose between indexing, get, and membership

Index a dictionary when a missing key represents an error. Use get when absence is expected, and use membership when later logic needs to distinguish a missing key from a key whose value is None.

Required and optional profile fields
user = {"name": "Ada", "role": "engineer"}

name = user["name"]
timezone = user.get("timezone", "UTC")

print(name)
print(timezone)
if "role" in user:
    print(user["role"])
Output
Ada
UTC
engineer
Back to quick reference ↑
03

Add, update, and merge values

Assignment and update mutate the existing dictionary. The merge operator creates a new dictionary, which is useful when the original mappings should remain unchanged. Later values replace earlier values for duplicate keys.

Mutating and non-mutating updates
user = {"name": "Ada", "role": "engineer"}
user["active"] = True
user.update({"role": "lead", "location": "London"})

defaults = {"theme": "light", "compact": False}
overrides = {"theme": "dark"}
combined = defaults | overrides

print(user)
print(combined)
Output
{'name': 'Ada', 'role': 'lead', 'active': True, 'location': 'London'}
{'theme': 'dark', 'compact': False}

Note: The dictionary merge operator requires Python 3.9 or newer.

Back to quick reference ↑
04

Remove keys deliberately

Use pop when the removed value is needed or when a fallback should make a missing key harmless. Use del when the key must exist and only removal matters.

Optional and required removal
user = {"name": "Ada", "role": "engineer", "active": True}

role = user.pop("role", None)
del user["active"]

print(role)
print(user)
Output
engineer
{'name': 'Ada'}
Back to quick reference ↑
05

Iterate over keys and values

Iteration over a dictionary yields keys. Calling items returns a dynamic view of key-value pairs. Dictionaries preserve insertion order, but sorting should be explicit when output requires another order.

Print keys and profile fields
user = {"name": "Ada", "role": "engineer"}

for key in user:
    print(key)

for key, value in user.items():
    print(f"{key}: {value}")
Output
name
role
name: Ada
role: engineer

Note: Do not add or remove dictionary keys while iterating over its live views; iterate over a list copy when structural changes are required.

Back to quick reference ↑
06

Build and initialize dictionary values

A dictionary comprehension creates a new mapping from an iterable. Setdefault is useful for initializing mutable grouping values, but a regular conditional or collections.defaultdict can be clearer when initialization logic grows.

Create squares and group tags
squares = {number: number ** 2 for number in range(4)}

groups = {}
tags = groups.setdefault("python", [])
tags.append("collections")

print(squares)
print(groups)
Output
{0: 0, 1: 1, 2: 4, 3: 9}
{'python': ['collections']}
Back to quick reference ↑

Local code tester

Try dictionary operations

Edit and run the Python locally to practice reading, updating, grouping, and iterating over a dictionary.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationData Structures — Dictionariesdocs.python.org
  2. Python Software FoundationMapping Types — dictdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback