Sub topic 1
Creating Dictionaries
A dictionary (dict) maps keys to values. You look up a value by its key instead of by a position, as you would with a list. This chapter covers the ways to build a dictionary, what the constructors do with duplicate keys, and the edge cases that catch people out. Later chapters cover hashable keys, lookup, mutation and the rest of the plan.
Prerequisites
This chapter assumes you already know:
- Basic Python syntax: variables, functions and f-strings.
- The core built-in types
str,int,listandtuple. forloops and conditionals.- The difference between mutable and immutable objects.
You do not need to know how dictionaries work internally. That comes in a later chapter.
The working model
A dictionary is a mutable collection of key-value pairs. Each key appears at most once. Each key is associated with exactly one value. The values can be any object, and they can repeat.
user = {"name": "Ada", "age": 36}
print(type(user)) # <class 'dict'>
print(len(user)) # 2
print(user["name"]) # Adalen() returns the number of pairs. Since Python 3.7, a dictionary also remembers the order in which keys were first inserted. A later chapter covers that guarantee in detail.
Dictionary literals
The most common way to create a dictionary is a literal: curly braces containing key: value pairs separated by commas.
empty = {}
prices = {"apple": 0.5, "pear": 0.75}
mixed = {1: "one", "two": 2, (3, 3): [3, 3, 3]}Keys in a literal can be of different types, and values can be anything, including lists and other dictionaries. A trailing comma after the last pair is allowed. It is a common style for multi-line literals because it keeps diffs small:
config = {
"host": "localhost",
"port": 8080,
"debug": True,
}Note that {} creates an empty dictionary, not an empty set. To create an empty set, use set().
print(type({})) # <class 'dict'>
print(type(set())) # <class 'set'>In a literal, the key is an expression. A bare name is evaluated, not treated as a string:
key = "color"
print({key: "red"}) # {'color': 'red'}
print({"key": "red"}) # {'key': 'red'}The dict() constructor
The dict() constructor builds a dictionary from other data. It accepts three main input styles. The example below shows all three producing equal dictionaries.
prices = {"apple": 0.5, "pear": 0.75}
other = dict(apple=0.5, pear=0.75)
pairs = dict([("apple", 0.5), ("pear", 0.75)])
print(prices == other == pairs) # TrueThe three forms are:
- A literal, as in
prices. - Keyword arguments, as in
other. Each argument name becomes a string key. - An iterable of key-value pairs, as in
pairs. Each item must be a sequence of exactly two elements.
You can also pass an existing mapping, and dict() makes a new dictionary from it. Keyword arguments can be combined with a positional argument. The keywords are applied last.
base = {"theme": "light", "font": 12}
copy_of_base = dict(base)
tweaked = dict(base, font=14)
print(tweaked) # {'theme': 'light', 'font': 14}Limits of keyword arguments
Keyword arguments are convenient, but the keys must be valid Python identifiers, and they are always strings. These calls fail or do not do what you want:
# dict(1=2) # SyntaxError: keyword argument names must be identifiers
# dict(my-key=1) # SyntaxError
print(dict(**{"my-key": 1})) # {'my-key': 1} (unpacking bypasses the check)Use a literal when keys are not identifiers, or are not strings. Keywords such as class or if also cannot be used as argument names.
Pairs must have exactly two items
An iterable of pairs is strict about its shape. A wrong-sized item raises ValueError:
try:
dict([("a", 1, 2)])
except ValueError as exc:
print(exc) # dictionary update sequence element #0 has length 3; 2 is requiredA common source of this error is a list of strings. Each string is itself an iterable, so a two-character string looks like a pair:
print(dict(["ab", "cd"])) # {'a': 'b', 'c': 'd'}That works by accident. A three-character string in the list would raise the ValueError above.
Building from two sequences with zip()
If you have keys and values in two separate sequences, zip() pairs them up. Wrapping the result in dict() gives a dictionary.
names = ["ana", "ben", "cy"]
scores = [90, 72, 85]
by_name = dict(zip(names, scores))
print(by_name) # {'ana': 90, 'ben': 72, 'cy': 85}zip() stops at the shortest input. If the lengths differ, extra items are dropped without an error. Since Python 3.10 you can ask for a check:
try:
dict(zip(["a", "b", "c"], [1, 2], strict=True))
except ValueError as exc:
print(exc) # zip() argument 2 is shorter than argument 1Use strict=True when a length mismatch would indicate a bug.
dict.fromkeys()
dict.fromkeys(iterable, value) creates a dictionary whose keys come from the iterable, all mapped to the same value. If you omit the value, it is None.
flags = dict.fromkeys(["read", "write", "exec"], False)
print(flags) # {'read': False, 'write': False, 'exec': False}
seen = dict.fromkeys("hello")
print(seen) # {'h': None, 'e': None, 'l': None, 'o': None}The second example shows a useful side effect. Duplicate keys collapse, and order is preserved, so list(dict.fromkeys(items)) removes duplicates from a list while keeping the first occurrence of each item.
items = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(items))) # [3, 1, 2]The shared-value trap
fromkeys() uses the same value object for every key. With an immutable value such as False or 0, this is harmless. With a mutable value such as a list, every key refers to the same list:
bad = dict.fromkeys(["a", "b"], [])
bad["a"].append(1)
print(bad) # {'a': [1], 'b': [1]}To give each key its own list, use a dictionary comprehension:
good = {k: [] for k in ["a", "b"]}
good["a"].append(1)
print(good) # {'a': [1], 'b': []}Dictionary comprehensions
A dictionary comprehension builds a dictionary from an iterable in one expression. The form is {key_expr: value_expr for item in iterable}. An optional if clause filters the items.
words = ["apple", "bob", "cat"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'bob': 3, 'cat': 3}
long_ones = {k: v for k, v in lengths.items() if v > 3}
print(long_ones) # {'apple': 5}Comprehensions are the right tool when the value depends on the key, or when each value must be a fresh object. A later chapter covers them in more depth. For now, remember that they are the safe alternative to fromkeys() for mutable values.
Duplicate keys
A dictionary cannot hold the same key twice. How duplicates are handled depends on how you create the dictionary, but in every case below the last value wins and no error is raised.
print({"a": 1, "a": 2}) # {'a': 2}
print(dict([("a", 1), ("a", 2)])) # {'a': 2}
print({k: v for k, v in [("a", 1), ("a", 2)]}) # {'a': 2}The position of the key stays where it was first inserted, while the value comes from the last assignment:
d = {"a": 1, "b": 2, "a": 3}
print(d) # {'a': 3, 'b': 2}Silently overwriting values is a common source of bugs when data comes from an external source. If duplicates matter, check for them yourself before building the dictionary.
pairs = [("a", 1), ("b", 2), ("a", 3)]
keys = [k for k, _ in pairs]
if len(keys) != len(set(keys)):
print("duplicate keys found")Duplicate literal keys are valid Python, but linters usually flag them, because they are almost always a typo.
Key equality across types
Two keys count as the same key when they are equal and have equal hashes. Some different-looking objects meet that test. The integer 1, the float 1.0 and the boolean True are all equal to each other:
d = {1: "int", 1.0: "float", True: "bool"}
print(d) # {1: 'bool'}The result keeps the first key (1) but takes the last value ("bool"). This is the same "first position, last value" rule as before. Mixing numeric types and booleans as keys is rarely a good idea.
Creating dictionaries from other dictionaries
There are several ways to start a new dictionary from an existing one:
dict(d)andd.copy()make a shallow copy.{**d}unpacks one dictionary into a new literal.d1 | d2(Python 3.9+) creates a merged dictionary.
a = {"x": 1}
b = {"y": 2}
print({**a, **b}) # {'x': 1, 'y': 2}
print(a | b) # {'x': 1, 'y': 2}These create a new dictionary and leave the originals unchanged. Merging and copying get their own chapters, including the behavior of nested values.
Choosing a construction method
| Situation | Best choice |
|---|---|
| Fixed, known pairs written in the source | Literal `{...}` |
| String keys that are valid identifiers, short and readable | `dict(key=value)` |
| Keys and values in two parallel sequences | `dict(zip(keys, values))` |
| Existing list of two-item pairs | `dict(pairs)` |
| Same immutable starting value for many keys | `dict.fromkeys(keys, value)` |
| Value computed from the key, or a fresh mutable value per key | Dictionary comprehension |
| Remove duplicates but keep order | `list(dict.fromkeys(items))` |
Common errors
- Using
{}for an empty set. It creates a dictionary. Useset(). - Mutable value in
fromkeys(). All keys share one object. Use a comprehension. - Unhashable keys. A list or another dictionary as a key raises
TypeError: unhashable type. The next chapter explains why. - Wrong-sized pairs.
dict()raisesValueErrorif an item does not have exactly two elements. - Silent duplicates. A repeated key overwrites without warning.
- Quoted versus bare keys. In a literal,
{name: 1}uses the value of the variablename. Indict(name=1),nameis the string"name".
Summary
You can create a dictionary with a literal, dict() (keywords, pairs or a mapping), zip(), dict.fromkeys() or a comprehension. Each has a place. The main hazards are shared mutable values in fromkeys(), silent overwriting of duplicate keys, and keys that are equal across types, such as 1 and True.
Exercise
What does this code print, and why? d = dict.fromkeys(["a", "b", "c"], []) d["a"].append(1) print(d) Rewrite the first line so that only the key "a" ends up with [1].
Show answer
It prints {'a': [1], 'b': [1], 'c': [1]}, because fromkeys() assigns the same list object to every key. Rewrite the first line as d = {k: [] for k in ["a", "b", "c"]}. Each key then gets its own new list, and the output is {'a': [1], 'b': [], 'c': []}.
Exercise
Given names = ["ana", "ben", "cy"] and scores = [90, 72], build a dictionary mapping names to scores so that a length mismatch raises an error instead of being ignored. Which Python version does your solution need?
Show answer
Use dict(zip(names, scores, strict=True)). This raises ValueError: zip() argument 2 is shorter than argument 1. The strict argument needs Python 3.10 or later.
Exercise
What is the value of {1: "a", 1.0: "b", True: "c"}, and which key and which value are kept?
Show answer
The result is {1: 'c'}. The three keys are equal and have the same hash, so they are one key. The dictionary keeps the first key object (1) in its original position and the last assigned value ("c").