In this article10
A list keeps things in order, and you find them by their position: fruits[0], fruits[1]… But often you don't want "the item at position 2". You want "the price of an apple", or "this user's email". That's what a dictionary is for. It stores key-value pairs: every value has a name, its key, and you get the value back by that name, without needing to know where it is. In this lesson you'll make dictionaries, read values from them (even from lists and dictionaries inside them), add and change values, and list all the keys and values. Press Run on any example, then Edit to change it.
A key and its value
A dictionary is written in curly braces { }. Inside, each pair is a key, a colon :, and its value. Commas separate the pairs:
{'key1': 'value1', 'key2': 'value2'}To get a value, write the dictionary's name and the key in square brackets:
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict['key1'])
print(my_dict['key2'])my_dict['key1'] means "the value stored under the key 'key1'", and that's 'value1'.
A real example: prices
Keys are usually words that describe the value. Here each fruit is a key, and its price is the value:
prices = {'apple': 400, 'orange': 250}
print(prices['apple'])
print(prices['orange'])You never had to know that the apple came first. You asked for 'apple', and you got its price. With a list you'd need to remember that the apple's price is at position 0, the orange's at position 1, and so on. That gets hard very fast.
A list or a dictionary?
Both hold many values. The difference is how you get a value back:
| List | Dictionary | |
|---|---|---|
| Written with | [ ] | { } with key: value |
| You get a value by its… | position (index): fruits[0] | key (name): prices['apple'] |
| Positions and slices | yes: fruits[0], fruits[1:3] | no: there are no positions |
| Use it for | things in an order: steps, a queue, a top 10 | things with a name: prices, settings, a person's details |
A good test: if you'd describe the data with "first, second, third…", use a list. If you'd describe it with "the price of…", "the name of…", "the age of…", use a dictionary.
Anything can go inside
A value can be anything: a number, a string, a list, a tuple, even another dictionary:
stuff = {'k1': 200, 'k2': ['apple', 'orange'], 'k3': ('time', 'year'), 'k4': {'insideKey': 100}}
print(stuff['k1'])
print(stuff['k2'])
print(stuff['k3'])
print(stuff['k4'])To reach something inside a value, add more brackets. Python reads them from left to right, one step at a time.
A dictionary inside a dictionary:
stuff = {'k1': 200, 'k2': ['apple', 'orange'], 'k3': ('time', 'year'), 'k4': {'insideKey': 100}}
print(stuff['k4']['insideKey'])stuff['k4']is the inner dictionary{'insideKey': 100}.['insideKey']then takes the value from that dictionary:100.
A tuple inside a dictionary:
stuff = {'k1': 200, 'k2': ['apple', 'orange'], 'k3': ('time', 'year'), 'k4': {'insideKey': 100}}
print(stuff['k3'][1])stuff['k3']is the tuple('time', 'year').[1]is a position now, because a tuple is ordered: position 1 is'year'.
A list inside a dictionary, and then a string method:
stuff = {'k1': 200, 'k2': ['apple', 'orange'], 'k3': ('time', 'year'), 'k4': {'insideKey': 100}}
print(stuff['k2'][0].upper())stuff['k2']is the list['apple', 'orange'].[0]is the first item:'apple'..upper()works on that string:'APPLE'.
This is what makes Python so flexible: whatever a step gives you (a list, a tuple, a dictionary, a string), you can keep going with what that type can do.
Adding a new key
To add a pair, give a new key a value with =:
d = {'k1': 2, 'k2': 3}
d['k3'] = 3
print(d)There was no 'k3' before, so Python adds it. The dictionary now has three pairs.
Changing a value
The same = on a key that already exists replaces its value:
d = {'k1': 2, 'k2': 3}
d['k2'] = 'new value'
print(d)Each key appears only once in a dictionary. So d['k2'] = … never makes a second 'k2'. It replaces the old value. The new value doesn't have to be the same type: here a number became a string.
Adding and changing look exactly the same. The only difference is whether the key was already there.
All the keys, all the values, all the pairs
Three methods show you what's inside:
d = {'k1': 2, 'k2': 'new value', 'k3': 3}
print(d.keys()) # only the keys
print(d.values()) # only the values
print(d.items()) # the pairs, each as (key, value)d.keys()givesdict_keys(['k1', 'k2', 'k3']): every key.d.values()givesdict_values([2, 'new value', 3]): every value.d.items()givesdict_items([('k1', 2), ('k2', 'new value'), ('k3', 3)]): every pair, each as a tuple(key, value).
The dict_keys(...) around the result just tells you what kind of collection it is. What matters is what's inside the brackets.
Common mistakes
Exercises
Show the answer
prices = {'apple': 400, 'orange': 250, 'banana': 150}
print(prices['banana'])
prices['kiwi'] = 300
prices['apple'] = 350
print(prices.keys())
print(prices.values())Adding the kiwi and changing the apple are the same kind of line. 'kiwi' was new, so it was added; 'apple' already existed, so its value was replaced.
Show the answer
student = {'name': 'lina', 'grades': [8, 9, 7], 'birthday': (2007, 5), 'address': {'city': 'Lund', 'zip': '22100'}}
print(student['address']['city']) # the inner dictionary, then its key
print(student['grades'][1]) # the list, then position 1
print(student['birthday'][0]) # the tuple, then position 0
print(student['name'].upper()) # the string, then .upper()Each line goes one step at a time, like in the lesson. The key gets you to the value. If the value is a list or a tuple, you use a position; if it's a dictionary, you use a key; if it's a string, you can use a string method.
Show the answer
student = {'name': 'lina', 'grades': [8, 9, 7], 'birthday': (2007, 5), 'address': {'city': 'Lund', 'zip': '22100'}}
student['email'] = 'lina@example.com'
student['address']['city'] = 'Malmö'
print(student)
print(student.items())student['address']['city'] = 'Malmö' reads like the city lookup you did in exercise 2, but with = at the end: first student['address'] reaches the inner dictionary, then ['city'] = … replaces the value there.
Quick check
Quick check
What does this print?
prices = {'apple': 400, 'orange': 250}
prices['orange'] = 300
print(prices['orange'])Why
'orange' already exists, so = replaces its value. Each key appears only once, so there's no error and no second 'orange'.
Quick check
stuff = {'k3': ('time', 'year')}. How do you get 'time'?
Why
First the key, stuff['k3'], gives the tuple. Then position [0] in the tuple gives 'time'. 'time' is a value, not a key, and the dictionary has no position 0.
Quick check
You want to store a phone book: names and their phone numbers. Which fits best?
Why
You'll look numbers up by name: phones['Ada']. That's exactly what a dictionary's keys are for. With a list you'd have to know at which position each person is.