What a dictionary is
A dictionary stores data as key-value pairs. Each key maps to one value, much like a paper dictionary where a word (the key) leads you to its definition (the value). Where a list finds items by their position, a dictionary finds them by a name you choose, which makes it the natural container for things like a student's scores, a person's details or a count per word.
You write a dictionary with curly braces. Each pair has the key, a colon and the value, and pairs are separated by commas:
scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(person["name"]) # Alice
print(len(person)) # 3
print(type(scores)) # <class 'dict'>
The square brackets after the dictionary name look up a value by its key, and len() counts the pairs. The type is called dict.
Building a dictionary
You can write all the pairs at once, as above, or start from an empty dictionary and add pairs one at a time. An empty dictionary is just a pair of braces:
scores = {}
scores["Alice"] = 95
scores["Bob"] = 87
print(scores) # {'Alice': 95, 'Bob': 87}
Assigning to a key that does not exist yet adds a new pair. Python prints dictionaries with single quotes around strings, even if you wrote double quotes in the code. Dictionaries remember the order in which keys were first added, so the pairs print and loop in that order.
What can be a key
Keys must be unique and unchangeable. Strings, numbers and tuples work as keys. Lists do not, because a list can be modified, and using one raises TypeError: unhashable type: 'list'. Values have no such restriction: they can be numbers, strings, lists or even other dictionaries, and different pairs in the same dictionary can hold different kinds of values.
Keys are compared exactly, so "Alice" and "alice" are two different keys. Numbers and strings are different too: the key 1 and the key "1" are not the same.
Common mistakes
- Writing the pair with an equals sign. A pair uses a colon:
{"Alice": 95}. Writing{"Alice" = 95}is a syntax error. - Forgetting quotes around text keys. In
{Alice: 95}, Python treatsAliceas a variable name, not as text, and raises aNameErrorif no such variable exists. - Repeating a key. A key can appear only once. In
{"a": 1, "a": 2}the later pair wins, and the result is{'a': 2}. No error is raised, so the earlier value is lost silently. - Mixing up dictionaries and lists. Square brackets build a list and curly braces build a dictionary. An empty
{}is an empty dictionary, not an empty set. - Missing commas between pairs. Every pair except the last needs a comma after it.
The exercise, step by step
This lesson has no starter code. You begin with an empty file and create the dictionary yourself. It must be named scores and hold three students.
- Choose the name. The variable is called
scores, and it goes at the top of the module. - Open the literal with a curly brace. This tells Python that a dictionary follows.
- Write the three pairs. Each key is the student's name as a string, followed by a colon and the score as a number:
"Alice"with 95,"Bob"with 87 and"Charlie"with 72. Separate the pairs with commas. - Close the brace. The whole dictionary fits on one line.
scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
The variable scores now holds three pairs. When a literal gets long, you can put each pair on its own line, which Python allows inside braces. That makes a bigger dictionary easier to read and to edit:
scores = {
"Alice": 95,
"Bob": 87,
"Charlie": 72,
}
The trailing comma after the last pair is allowed. Both forms create the same dictionary.
Key takeaways
- A dictionary maps keys to values and is written with curly braces:
{key: value, key: value}. - Look values up with
d[key]and count the pairs withlen(d). - Keys are unique, case sensitive and must be unchangeable, such as strings, numbers and tuples.
{}creates an empty dictionary, and assigning to a new key adds a pair.