ShareYourGroupShareYourGroupPython

Lesson 14 of 21 · about 6 minutes with the exercises

Dictionaries

A dictionary stores values under names. In a real dictionary you look up a word and find its meaning. In a Python dictionary you look up a key and find its value. Use one whenever your data is a set of labelled facts: a student's details, the price of each item, the number of votes for each choice.

Making a dictionary

Use curly brackets. Each entry is a key, a colon and a value.

student = {"name": "Asha", "class": 8, "city": "Ludhiana"}
print(student)
print(len(student))

Output

{'name': 'Asha', 'class': 8, 'city': 'Ludhiana'}
3

Keys are usually strings. They must be unique: a second entry with the same key replaces the first. Values can be anything, including lists and other dictionaries.

Reading a value

Put the key in square brackets.

student = {"name": "Asha", "class": 8, "city": "Ludhiana"}
print(student["name"])
print(student["class"] + 1)

Output

Asha
9

Asking for a key that is not there stops the program with a KeyError.

student = {"name": "Asha", "class": 8}
print(student["phone"])

What Python says

Traceback (most recent call last):
  File "example.py", line 2, in <module>
    print(student["phone"])
          ~~~~~~~^^^^^^^^^
KeyError: 'phone'

The get method is the safe way to read. It returns None, or a default you choose, when the key is missing.

student = {"name": "Asha", "class": 8}
print(student.get("phone"))
print(student.get("phone", "not given"))
print("phone" in student)

Output

None
not given
False

More on this on the KeyError page.

Adding, changing and deleting

Assigning to a key adds it if it is new and changes it if it exists. There is no separate append.

prices = {"tea": 10, "samosa": 15}
prices["lassi"] = 40
prices["tea"] = 12
print(prices)
del prices["samosa"]
print(prices)
removed = prices.pop("lassi")
print(removed, prices)

Output

{'tea': 12, 'samosa': 15, 'lassi': 40}
{'tea': 12, 'lassi': 40}
40 {'tea': 12}

Looping

Looping over a dictionary gives its keys. Use .items() to get the key and value together, which is what you want most of the time.

prices = {"tea": 12, "samosa": 15, "lassi": 40}
for item in prices:
    print(item)
for item, price in prices.items():
    print(f"{item:<8}Rs {price}")
print(sum(prices.values()))

Output

tea
samosa
lassi
tea     Rs 12
samosa  Rs 15
lassi   Rs 40
67

.keys() and .values() give just one side. A dictionary keeps its entries in the order you added them.

Counting with a dictionary

Counting how often each thing appears is a job dictionaries do well. get(key, 0) reads the current count, or 0 the first time.

votes = ["tea", "coffee", "tea", "lassi", "tea", "coffee"]
count = {}
for v in votes:
    count[v] = count.get(v, 0) + 1
print(count)

Output

{'tea': 3, 'coffee': 2, 'lassi': 1}

To find the winner, ask max to compare the keys by their counts.

count = {"tea": 3, "coffee": 2, "lassi": 1}
winner = max(count, key=count.get)
print(winner, count[winner])

Output

tea 3

Sorting a dictionary

sorted on a dictionary sorts its keys. To sort by value, sort the items with a key function.

marks = {"Ravi": 91, "Asha": 78, "Meena": 85}
for name in sorted(marks):
    print(name, marks[name])
by_marks = sorted(marks.items(), key=lambda pair: pair[1], reverse=True)
print(by_marks)

Output

Asha 78
Meena 85
Ravi 91
[('Ravi', 91), ('Meena', 85), ('Asha', 78)]

A list of dictionaries

Most real data looks like this: a list of records, where each record is a dictionary with the same keys. If you later read spreadsheets or data from websites, this is the shape you will get.

students = [
    {"name": "Asha", "marks": 78},
    {"name": "Ravi", "marks": 91},
    {"name": "Meena", "marks": 85},
]
for s in students:
    if s["marks"] >= 80:
        print(s["name"])
average = sum(s["marks"] for s in students) / len(students)
print(round(average, 1))

Output

Ravi
Meena
84.7

A dictionary inside a dictionary

school = {
    "Asha": {"class": 8, "house": "Blue"},
    "Ravi": {"class": 9, "house": "Red"},
}
print(school["Ravi"]["house"])

Output

Red

Read it left to right: first pick Ravi's record, then pick the house from it.

Common mistakes

Try it yourself

Exercise 1. Make a dictionary of three fruits and their prices per kg. Print the price of one fruit, then add a fourth fruit and print how many there are.

Show one answer
fruit = {"mango": 120, "banana": 50, "apple": 180}
print(fruit["banana"])
fruit["guava"] = 80
print(len(fruit))

Output

50
4

Exercise 2. Count how many times each letter appears in the word "banana".

Show one answer
count = {}
for ch in "banana":
    count[ch] = count.get(ch, 0) + 1
print(count)

Output

{'b': 1, 'a': 3, 'n': 2}

Exercise 3. A shop's stock is {"pen": 40, "book": 0, "bag": 7, "ink": 0}. Print the names of the items that are out of stock.

Show one answer
stock = {"pen": 40, "book": 0, "bag": 7, "ink": 0}
for item, qty in stock.items():
    if qty == 0:
        print(item)

Output

book
ink

Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.