Sub topic 1
Creating Dictionaries
Prerequisites
This chapter assumes you know basic Python syntax (variables, functions, f-strings), the built-in types str, int, list and tuple, for loops and conditionals, and the difference between mutable and immutable objects.
What a dictionary is
A dictionary (type dict) maps keys to values. You look up a value by its key, not by a position. Each key appears at most once, and each key is paired with exactly one value. Dictionaries are among the most used built-in types in Python, so the ways to create them are worth knowing well.
Three ways to build a dictionary
The most common form is the literal: curly braces holding key: value pairs separated by commas. You can also call dict() with keyword arguments, or pass it an iterable of key-value pairs.
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) # TrueAll three produce equal dictionaries. Each form suits a different situation:
| Form | Best for | Limitation |
|---|---|---|
| Literal `{...}` | Data you write out by hand | None |
| `dict(name=value)` | Short dictionaries with simple names | Keys must be valid identifiers and become strings |
| `dict(iterable)` | Pairs produced by other code, such as `zip()` | Each item must hold exactly two elements |
Keyword arguments always create string keys. If you need integer keys or keys with spaces, use a literal or a list of pairs.
An empty dictionary is {}. Note that {} makes a dictionary, not a set. For an empty set, write set().
empty = {}
print(type(empty)) # <class 'dict'>Building from two sequences
A common task is to combine a list of keys with a list of values. zip() pairs them up, and dict() turns the pairs into a dictionary.
keys = ["name", "role"]
values = ["Ada", "admin"]
user = dict(zip(keys, values))
print(user) # {'name': 'Ada', 'role': 'admin'}If the two sequences differ in length, zip() stops at the shorter one and drops the extra items without warning. Check the lengths first if a mismatch would be a bug.
What happens with duplicate keys
A key can only appear once. If a literal repeats a key, the last value wins and no error is raised.
settings = {"theme": "light", "theme": "dark"}
print(settings) # {'theme': 'dark'}This is easy to miss in a long literal. Linters often warn about it, so it helps to run one.
How a dictionary is built, step by step
When Python builds a dictionary from pairs, it handles each pair in order. A new key adds an entry. A key that already exists has its value replaced.
This explains the duplicate-key behavior above. The second "theme" pair finds the key already present and replaces its value.
Common errors
- Passing a flat list to
dict().dict(["a", "b"])fails, or gives surprising results, because each item must be a pair. Strings of exactly two characters, such as"ab", are treated as a pair, which hides the mistake. - Using a non-identifier name with keyword arguments.
dict(first-name="Ada")is a syntax error. Use a literal instead. - Expecting
{}to be a set. It is a dictionary.
Exercise
You have the lists names = ["ana", "ben", "cy"] and ages = [31, 28]. What does dict(zip(names, ages)) return, and why is this a risk?
Show answer
It returns {'ana': 31, 'ben': 28}. zip() stops at the shorter list, so "cy" is silently dropped. If the lists should be the same length, check len(names) == len(ages) before building the dictionary.
Exercise
What does {"a": 1, "b": 2, "a": 3} evaluate to?
Show answer
{'a': 3, 'b': 2}. The repeated key "a" keeps its original position, but its value is replaced by the last one given.