EN · USD

Language

Prices in

USDUSD · your currency EuroEUR · what you pay

You always pay in euros. Other currencies are a guide at today's rate.

Become a tutor Sign up
Try:
Search tips: combine words
python list
Articles with all the words
"for loop"
The exact words, in this order
python OR javascript
Either word
functions -arrow
Leave out articles with a word
title:booleans
Only in the title
code:append
Only in code examples
subject:python
In one subject
by:maximilian
By one writer
series:javascript
In one series
level:beginner
At one level
Try:
Search tips: combine words
python list
Articles with all the words
"for loop"
The exact words, in this order
python OR javascript
Either word
functions -arrow
Leave out articles with a word
title:booleans
Only in the title
code:append
Only in code examples
subject:python
In one subject
by:maximilian
By one writer
series:javascript
In one series
level:beginner
At one level

Python Beginner English 10 min read

Python dictionaries: keys, values and everything inside

Store values under names instead of positions: make dictionaries, read values (even from lists, tuples and dictionaries inside them), add and change keys, and see every key, value and pair with keys(), values() and items().

Series · Lesson 3 of 3 Python, one lesson a day
In this article10
  1. A key and its value
  2. A real example: prices
  3. A list or a dictionary?
  4. Anything can go inside
  5. Adding a new key
  6. Changing a value
  7. All the keys, all the values, all the pairs
  8. Common mistakes
  9. Exercises
  10. Quick check

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:

ListDictionary
Written with[ ]{ } with key: value
You get a value by its…position (index): fruits[0]key (name): prices['apple']
Positions and slicesyes: fruits[0], fruits[1:3]no: there are no positions
Use it forthings in an order: steps, a queue, a top 10things 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'])
  1. stuff['k4'] is the inner dictionary {'insideKey': 100}.
  2. ['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])
  1. stuff['k3'] is the tuple ('time', 'year').
  2. [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())
  1. stuff['k2'] is the list ['apple', 'orange'].
  2. [0] is the first item: 'apple'.
  3. .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() gives dict_keys(['k1', 'k2', 'k3']): every key.
  • d.values() gives dict_values([2, 'new value', 3]): every value.
  • d.items() gives dict_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.

More from Maximilian Bahrami