Python Dictionary Examples
A runnable cookbook of everyday Python dictionary tasks — merge, get, keys, values, items, iterate, invert and count — each a short snippet you can run in the browser.
Overview
Short, copy-paste examples for the most common dictionary tasks in Python. Run any of them in the online Python compiler.
Examples
Merge two dictionaries
a = {"x": 1}
b = {"y": 2}
print(a | b) # {'x': 1, 'y': 2} (Python 3.9+)
Get a value safely with get()
d = {"name": "Ada"}
print(d.get("name")) # Ada
print(d.get("email", "n/a")) # n/a (default, no KeyError)
List the keys
d = {"a": 1, "b": 2, "c": 3}
print(list(d.keys())) # ['a', 'b', 'c']
List the values
d = {"a": 1, "b": 2, "c": 3}
print(list(d.values())) # [1, 2, 3]
Loop over items()
prices = {"pen": 3, "book": 12}
for name, cost in prices.items():
print(name, cost)
# pen 3
# book 12
Iterate keys and values separately
d = {"a": 1, "b": 2}
for k in d:
print(k, d[k])
# a 1
# b 2
Build a dict with a comprehension
words = ["hi", "hey", "hello"]
print({w: len(w) for w in words}) # {'hi': 2, 'hey': 3, 'hello': 5}
Invert keys and values
d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()}) # {1: 'a', 2: 'b'}
Count occurrences
from collections import Counter
votes = ["a", "b", "a", "c", "a"]
print(dict(Counter(votes))) # {'a': 3, 'b': 1, 'c': 1}
Frequently asked questions
How do I merge two dictionaries in Python?
On Python 3.9+, use
a | b; on older versions use {a, b}. Both return a new dict where later keys win.How do I read a dictionary value without a KeyError?
Use
d.get(key, default) — it returns the default (or None) instead of raising when the key is missing.How do I invert a dictionary?
Use a comprehension over its items:
{v: k for k, v in d.items()}. Values must be unique and hashable.