Skip to content
Educora
Intermediate16 min8 / 42

Dictionaries

Store data as key: value pairs: create a dictionary, change it, loop over it and use it for counting.

Check yourself
In this lesson you will learn
  • Create a dictionary and get values by their keys
  • Add, change and delete pairs, and read safely with get()
  • Loop over a dictionary with items() and count frequencies with it

Think of the contacts on your phone: you look up “Mum” and see the number at once — you don't need to know which position the contact has in the list. A paper dictionary works the same way: you find a word, and its meaning is written next to it. In Python this kind of data is stored in a dictionary (dict): every value has its own key.

Creating a dictionary

Definition
Dictionary (dict)

A collection of key: value pairs written in curly braces {}. A value is found by its key, not by an index: student['name'].

Python
student = {'name': 'Leyla', 'age': 14, 'city': 'Ganja'}
print(student)
print(student['name'])
print(len(student))
print(student.get('email'))
print(student.get('email', 'no email'))
▸ Expected output
{'name': 'Leyla', 'age': 14, 'city': 'Ganja'}
Leyla
3
None
no email

If you read a key that is not in the dictionary, like student['email'], Python raises a KeyError. The get() method does not: if the key is missing, it returns None (Python's special value meaning “nothing”) or whatever you pass as the second argument.

Changing a dictionary

Adding a new pair and changing an existing value are written the same way: student['age'] = 15. If the key exists, the value is updated; if not, a new pair is created. del removes a pair, and in checks whether a key is in the dictionary.

Python
student = {'name': 'Leyla', 'age': 14}
student['age'] = 15
student['grade'] = 9
print(student)

del student['grade']
print('grade' in student, 'name' in student)
▸ Expected output
{'name': 'Leyla', 'age': 15, 'grade': 9}
False True

Looping over a dictionary

keys() gives all the keys, values() all the values and items() the (key, value) pairs. In a loop over items() you can unpack each pair straight into two variables — just like in the lesson on tuples.

Python
prices = {'bread': 0.8, 'milk': 1.9, 'cheese': 6.5}
for item, price in prices.items():
    print(f'{item}: {price:.2f} AZN')

print('Items:', list(prices.keys()))
print(f'Total: {sum(prices.values()):.2f} AZN')
▸ Expected output
bread: 0.80 AZN
milk: 1.90 AZN
cheese: 6.50 AZN
Items: ['bread', 'milk', 'cheese']
Total: 9.20 AZN
1 / 6

Counting with a dictionary

One of the most useful jobs for a dictionary is counting how many times something appears. For each word we write counts.get(word, 0) + 1: when a word appears for the first time, get returns 0; after that, 1 is added to the old count.

Python
text = 'the cat and the dog and the bird'
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
print('the:', counts['the'])
▸ Expected output
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
the: 3

Nested structures

A dictionary value can be of any type — for example, a list. With this structure you can build a simple class register: the key is a student's name and the value is the list of their grades.

Python
journal = {
    'Aysel': [5, 4, 5],
    'Murad': [4, 3, 4],
    'Nigar': [5, 5, 5],
}
for name, grades in journal.items():
    avg = sum(grades) / len(grades)
    print(f'{name}: {avg:.1f}')

journal['Murad'].append(5)
print(journal['Murad'])
▸ Expected output
Aysel: 4.7
Murad: 3.7
Nigar: 5.0
[4, 3, 4, 5]

A dictionary is especially handy for:

  • looking values up quickly by a name or code: contacts, product prices;
  • counting: how often words, votes or grades appear;
  • grouping: each class with its own list of students;
  • describing the properties of one thing: name, age, city.
Python
import json

student = {'name': 'Leyla', 'age': 14, 'city': 'Ganja'}
text = json.dumps(student)
print(text)

back = json.loads(text)
print(back['city'])
▸ Expected output
{"name": "Leyla", "age": 14, "city": "Ganja"}
Ganja
Exercise

Add the key 'tea' with the price 3.2 to the prices dictionary and change the price of 'bread' to 1.0. Then use .items() to print every product in the form apple: 1.50, and finally print Total: with the sum of all prices (with two digits after the point).

Exercise · Python
prices = {'apple': 1.5, 'bread': 0.8, 'milk': 1.9}
# 1) add tea for 3.2 and change bread to 1.0
# 2) print each item like: apple: 1.50
# 3) print Total: and the sum of all prices
▸ Expected output
apple: 1.50
bread: 1.00
milk: 1.90
tea: 3.20
Total: 7.60
Exercise

A class voted for their favourite dish. Count the votes for each dish with a dictionary and .get(), then print the dishes in alphabetical order in the form dolma: 2. Finally print Winner: followed by the dish with the most votes.

Exercise · Python
votes = ['plov', 'dolma', 'plov', 'kebab', 'dolma', 'plov']
counts = {}
# 1) count the votes for each dish
# 2) print the dishes in alphabetical order like: dolma: 2
# 3) print Winner: and the dish with the most votes
▸ Expected output
dolma: 2
kebab: 1
plov: 3
Winner: plov

Key points

  • A dictionary holds key: value pairs in {}; a value is found by its key.
  • d[key] = value adds a pair or updates a value; del d[key] removes a pair.
  • get() does not fail on a missing key; it returns None or the default you give.
  • Looping over items() gives you the key and the value together at each step.
  • Keys must be unique and of an unchangeable type.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
If d = {'a': 1, 'b': 2}, what is d['b']?