What a dictionary is
A dictionary maps keys to values, like a real dictionary maps words to definitions. Lookups by key are extremely fast no matter how big the dict grows. Since Python 3.7 dictionaries keep insertion order.
person = {"name": "Ada", "born": 1815, "languages": ["English", "French"]}
print(person["name"])
print(person["languages"][1])
person["born"] = 1816 # update
person["country"] = "England" # add
print(person)
print(len(person), "name" in person)Keys must be immutable (strings, numbers, tuples). Values can be anything, including other dictionaries.
Safe access with get() and setdefault()
Reading a missing key with [] raises KeyError. get() returns a default instead:
stock = {"apple": 3}
print(stock.get("apple"))
print(stock.get("pear")) # None
print(stock.get("pear", 0)) # custom default
# count words - the classic dict pattern
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
# group values into lists
groups = {}
for w in text.split():
groups.setdefault(len(w), []).append(w)
print(groups)Looping over a dictionary
prices = {"coffee": 3.5, "tea": 2.0, "cake": 4.25}
for item in prices: # keys
print(item, end=" ")
print()
for item, price in prices.items(): # key/value pairs
print(f"{item:8} ${price:.2f}")
print(list(prices.keys()))
print(list(prices.values()))
print(sum(prices.values()))
print(max(prices, key=prices.get)) # key with largest valueRemoving, merging and comprehensions
d = {"a": 1, "b": 2, "c": 3}
removed = d.pop("b")
del d["a"]
print(d, removed)
defaults = {"theme": "light", "size": 12}
user = {"size": 14}
settings = defaults | user # merge, right wins (3.9+)
print(settings)
defaults.update(user) # in place
print(defaults)
squares = {n: n * n for n in range(1, 6)}
flipped = {v: k for k, v in squares.items()}
print(squares)
print(flipped)Nested dictionaries
Real data (JSON from an API, a config file, a database row) is almost always nested:
users = {
"u1": {"name": "Ada", "roles": ["admin"]},
"u2": {"name": "Linus", "roles": ["dev", "ops"]},
}
for uid, info in users.items():
print(uid, info["name"], ", ".join(info["roles"]))
users["u2"]["roles"].append("lead")
print(users["u2"])Sets
A set is an unordered collection of unique values. Use it to remove duplicates and to ask "is X in here?" quickly:
tags = {"python", "code", "python", "learn"}
print(tags) # duplicates gone, order arbitrary
tags.add("mobile")
tags.discard("code")
print("learn" in tags, len(tags))
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # union
print(a & b) # intersection
print(a - b) # difference
print(a ^ b) # symmetric difference
print({1, 2} <= a) # subset?
unique = list(set([3, 1, 3, 2, 1]))
print(sorted(unique))An empty set is set(), not {} — the latter is an empty dictionary. Set items, like dict keys, must be immutable.
You now know the four core collections. Next: packaging code into reusable functions.
Frequently asked questions
What is the difference between a list and a dictionary?
A list is an ordered sequence you index by position (0, 1, 2…). A dictionary stores key–value pairs you look up by key. Use a dict when items have natural names or IDs.
How do I check if a key exists in a dictionary?
Use the in operator: if 'name' in person. Or use person.get('name') which returns None (or a default) instead of raising KeyError.
Are Python dictionaries ordered?
Yes, since Python 3.7 dictionaries preserve insertion order as a language guarantee.
When should I use a set instead of a list?
Use a set when you need unique items or fast membership tests and do not care about order. Checking x in a_set is O(1); in a list it is O(n).