A Python dictionary stores values under keys, so you can retrieve, update, and remove data by name.
Create a dictionary
Use braces for a literal dictionary. Each key is followed by a value, and pairs are separated by commas.
user = {"name": "Alice", "age": 30, "role": "developer"}
print(user)
print(user["name"])
A key lookup returns the value attached to that key. Square brackets are strict, which makes a missing key raise KeyError and exposes a data mistake early.
Read keys safely with get
Use get when a key may be absent and a default value is useful. The dictionary stays unchanged.
settings = {"theme": "dark", "notifications": True}
print(settings.get("theme"))
print(settings.get("font_size", 16))
The second get call returns 16 without adding font_size to settings. Choose square brackets when absence should stop the operation, and choose get when the next step can continue with a default.
Add and update items
Assigning to a new key adds a pair. Assigning to an existing key replaces its value.
profile = {"name": "Ada", "language": "Python"}
profile["experience"] = "senior"
profile["language"] = "Python 3"
print(profile)
Loop through a dictionary
Use items when you need each key and value together. Use keys or values when only one side is needed.
scores = {"Ada": 94, "Grace": 91}
for name, score in scores.items():
print(name, score)
Remove entries
The pop method removes a key and returns its value. Give pop a default when deletion should be safe if the key is absent.
cache = {"page": "/home", "format": "html"}
removed = cache.pop("format", None)
print(removed)
print(cache)
Dictionary comprehension
A dictionary comprehension builds a new dictionary from an iterable. Put the transformation and any filter in the same expression only when the rule remains easy to read.
numbers = [1, 2, 3, 4]
squares = {n: n * n for n in numbers if n % 2 == 0}
print(squares)
The comprehension keeps even numbers and maps each one to its square.
Common dictionary questions
Can a dictionary have duplicate keys? Assigning the same key again keeps the latest value.
How do you check whether a key exists? Use the in operator with the dictionary.
Does get add a missing key? It returns the default without changing the dictionary.
Python dictionaries are a good fit when your next operation starts with a name or identifier. Use a list when position is the data you need, then choose strict lookup or a default based on whether missing data is an error.

