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)
Ada French {'name': 'Ada', 'born': 1816, 'languages': ['English', 'French'], 'country': 'England'} 4 True

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)
3 None 0 {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1} {3: ['the', 'cat', 'and', 'the', 'hat', 'and', 'the', 'bat']}

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 value
coffee tea cake coffee $3.50 tea $2.00 cake $4.25 ['coffee', 'tea', 'cake'] [3.5, 2.0, 4.25] 9.75 cake

Removing, 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)
{'c': 3} 2 {'theme': 'light', 'size': 14} {'theme': 'light', 'size': 14} {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} {1: 1, 4: 2, 9: 3, 16: 4, 25: 5}

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"])
u1 Ada admin u2 Linus dev, ops {'name': 'Linus', 'roles': ['dev', 'ops', 'lead']}
Build a word counter in the app — the Coding Python app runs real Python 3 on your phone, with examples, quizzes and challenges built in.
Get it free

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))
{'code', 'python', 'learn'} True 3 {1, 2, 3, 4, 5} {3, 4} {1, 2} {1, 2, 5} True [1, 2, 3]

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).