Asiman Data School

Module 1, topic 5, week 3, Tuesday

Data structures continued: dictionaries, sets, and comprehensions

Dictionaries and their methods, loops over dictionaries, sets and set operations, and comprehensions

Introduction: dictionaries, sets and comprehensions

A beginner-friendly guide to the next two data structures of Python, dictionaries and sets, and to comprehensions, the short way to build a list, a dictionary or a set in one line. It starts from the simplest examples and gets harder step by step. It shows every everyday dictionary operation (get, update, pop, keys, values, items and more), every set operation (union, intersection, difference and more), and how to use if/else, for and while with both. Then it walks through 26 solved problems from easy to medium-hard. At the end there are practice problems.

You should already know variables, data types, operators, if/else, loops, functions, lists and tuples.

What you will learn

  1. 1.What a dictionary is, and how to create, read, change, grow and shrink one
  2. 2.Every common dictionary method and when to use it
  3. 3.How to go through a dictionary with loops and if/else, and the counting pattern
  4. 4.Dictionaries inside lists and lists inside dictionaries
  5. 5.What a set is, and how to add and remove items
  6. 6.Set operations: union, intersection, difference, symmetric difference, subset
  7. 7.How list, tuple, dictionary and set differ, and when to use each
  8. 8.List, dictionary and set comprehensions, with and without a condition
  9. 9.26 solved problems and practice problems

1Dictionaries: creating and reading

1.1What is a dictionary?

Imagine you store the grades of three students in a list:

Python
grades = [85, 92, 78]
print(grades[1])

Output

92

Whose grade is grades[1]? You must remember that position 1 is Murad. With 500 students that is impossible. A dictionary stores each value together with a name for it, called a key:

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
print(grades["Murad"])

Output

92

Change it and run: print the grade of "Leyla".

Real-life picture: a real dictionary. You look up a word (the key) and get its meaning (the value). A phone book works the same way: name, then number.

What is a dictionary?
ListDictionary
You find a value byits position (index): grades[1]its key: grades["Murad"]
Written with[ ]{ } with key: value pairs

A list: each value has a position

085
192
278

grades[1] gives 92

A dictionary: each value has a key

"Aylin"85
"Murad"92
"Leyla"78

grades["Murad"] gives 92

The filled boxes are the keys, the outlined boxes are the values. You never need to remember a position.

1.2Creating dictionaries

A dictionary is written in curly brackets. Each item is a pair key: value, and the pairs are separated by commas:

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
empty = {}

print(student)
print(prices)
print(empty)
print(type(student))

Output

{'name': 'Aylin', 'age': 20, 'city': 'Baku'}
{'apple': 1.5, 'bread': 0.8, 'milk': 2.0}
{}
<class 'dict'>

Change it and run: add a fourth pair to student, for example "email".

  • The keys are usually text or numbers. The values can be anything: numbers, text, lists, even other dictionaries.
  • A dictionary can be empty: {}.

A long dictionary is easier to read with one pair per line:

Python
student = {
    "name": "Aylin",
    "age": 20,
    "city": "Baku",
}
print(student)

Output

{'name': 'Aylin', 'age': 20, 'city': 'Baku'}

1.3How many pairs? len()

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
print(len(student))
print(len({}))

Output

3
0

1.4Making a dictionary with dict()

Python
student = dict(name="Aylin", age=20)
print(student)

pairs = [("apple", 1.5), ("bread", 0.8)]
prices = dict(pairs)
print(prices)

Output

{'name': 'Aylin', 'age': 20}
{'apple': 1.5, 'bread': 0.8}

dict() can build a dictionary from name=value arguments, or from a list of pairs (tuples with two items).

1.5Square brackets: dictionary[key]

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
print(student["name"])
print(student["age"])

Output

Aylin
20

Change it and run: print student["city"].

A key that does not exist gives an error:

Python
student = {"name": "Aylin", "age": 20}
print(student["email"])

Error

KeyError: 'email'

A dictionary has no positions. student[0] does not mean "the first item": Python looks for a key that is the number 0.

Python
student = {"name": "Aylin", "age": 20}
print(student[0])

Error

KeyError: 0

1.6get(key): reading without an error

get gives the value if the key exists. If it does not, get gives None instead of an error:

Python
student = {"name": "Aylin", "age": 20}
print(student.get("name"))
print(student.get("email"))

Output

Aylin
None

You can choose what get gives back for a missing key. This is called the default:

Python
student = {"name": "Aylin", "age": 20}
print(student.get("email", "no email"))
print(student.get("age", 0))

Output

no email
20

Change it and run: ask for "city" with the default "unknown".

1.7Is the key there? in and not in

in checks the keys, not the values:

Python
student = {"name": "Aylin", "age": 20}
print("name" in student)
print("email" in student)
print("Aylin" in student)
print("email" not in student)

Output

True
False
False
True

Change it and run: check 20 in student. Is 20 a key?

"Aylin" in student is False, because "Aylin" is a value, not a key.

Is the key there? in and not in
WayKey existsKey is missing
d[key]the valueKeyError
d.get(key)the valueNone
d.get(key, default)the valuethe default
key in dTrueFalse

Try it yourself

Create a dictionary with your name, age and city, and print each value on its own line.
Show a hint
Three pairs in curly brackets, then three lines like print(me["name"]).
Show the solution
Python
me = {"name": "Aylin", "age": 20, "city": "Baku"}
print(me["name"])
print(me["age"])
print(me["city"])

Output

Aylin
20
Baku

2Adding, changing and removing

2.1Adding and changing

Dictionaries are mutable (changeable), like lists.

2.2dictionary[key] = value

The same line does two different jobs:

  • If the key exists, its value is changed.
  • If the key does not exist, a new pair is added.
Python
student = {"name": "Aylin", "age": 20}

student["age"] = 21             # the key exists: change
student["city"] = "Baku"        # the key is new: add
print(student)

Output

{'name': 'Aylin', 'age': 21, 'city': 'Baku'}

Change it and run: add a pair "email", then change the name.

A very common pattern is to start with an empty dictionary and fill it:

Python
prices = {}
prices["apple"] = 1.5
prices["bread"] = 0.8
print(prices)

Output

{'apple': 1.5, 'bread': 0.8}

Changing a number that is stored in a dictionary:

Python
stock = {"apple": 10, "bread": 4}
stock["apple"] = stock["apple"] + 5
stock["bread"] -= 1
print(stock)

Output

{'apple': 15, 'bread': 3}

Change it and run: sell 3 apples: subtract 3.

2.3update(other): add or change several pairs at once

Python
student = {"name": "Aylin", "age": 20}
student.update({"age": 21, "city": "Baku", "email": "aylin@example.com"})
print(student)

Output

{'name': 'Aylin', 'age': 21, 'city': 'Baku', 'email': 'aylin@example.com'}

age existed, so it was changed. city and email were new, so they were added.

2.4setdefault(key, value): add only if the key is missing

Python
student = {"name": "Aylin"}
student.setdefault("city", "Baku")
student.setdefault("name", "Murad")
print(student)

Output

{'name': 'Aylin', 'city': 'Baku'}

Change it and run: add a line student.setdefault("age", 20).

city was missing, so it was added. name already existed, so nothing changed.

setdefault(key, value): add only if the key is missing
WayKey existsKey is missing
d[key] = valuechanges the valueadds the pair
d.update({...})changes the valuesadds the pairs
d.setdefault(key, value)does nothingadds the pair

2.5pop(key): remove a pair and give its value back

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
age = student.pop("age")
print(age)
print(student)

Output

20
{'name': 'Aylin', 'city': 'Baku'}

Change it and run: pop "city" too and print what is left.

A missing key gives an error, unless you give a default:

Python
student = {"name": "Aylin"}
student.pop("email")

Error

KeyError: 'email'
Python
student = {"name": "Aylin"}
print(student.pop("email", "nothing to remove"))

Output

nothing to remove

2.6del: delete a pair

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
del student["city"]
print(student)

Output

{'name': 'Aylin', 'age': 20}

del does not give the value back, and a missing key is a KeyError.

2.7popitem(): remove the last pair

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
last = student.popitem()
print(last)
print(student)

Output

('city', 'Baku')
{'name': 'Aylin', 'age': 20}

Change it and run: call popitem() twice.

popitem gives the removed pair back as a tuple (key, value).

2.8clear(): remove everything

Python
student = {"name": "Aylin", "age": 20}
student.clear()
print(student)
print(len(student))

Output

{}
0
clear(): remove everything
ToolRemovesGives backMissing key
d.pop(key)that pairthe valueKeyError
d.pop(key, default)that pairthe value, or the defaultno error
del d[key]that pairnothingKeyError
d.popitem()the last pairthe pair as a tupleKeyError if the dictionary is empty
d.clear()everythingnothingno error

Press a line and watch what happens to the dictionary.

student = {"name": "Aylin", "age": 20}
'name''Aylin'
'age'20

Filled boxes are keys, outlined boxes are values.

Try it yourself

Start with profile = {"name": "Aylin", "city": "Baku"}. Add "age" with 20, change the city to "Ganja", remove "name" with pop and print the removed value, then print the dictionary.
Show a hint
Adding and changing both use profile[key] = value. removed = profile.pop("name") removes the pair and stores its value.
Show the solution
Python
profile = {"name": "Aylin", "city": "Baku"}
profile["age"] = 20
profile["city"] = "Ganja"
removed = profile.pop("name")
print(removed)
print(profile)

Output

Aylin
{'city': 'Ganja', 'age': 20}

3Keys, values, rules for keys and copying

3.1keys(), values(), items()

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
print(prices.keys())
print(prices.values())
print(prices.items())

Output

dict_keys(['apple', 'bread', 'milk'])
dict_values([1.5, 0.8, 2.0])
dict_items([('apple', 1.5), ('bread', 0.8), ('milk', 2.0)])
  • keys() gives all the keys.
  • values() gives all the values.
  • items() gives all the pairs, each one as a tuple (key, value).

Wrap them in list() when you need a real list (for example to use an index):

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
names = list(prices.keys())
print(names)
print(names[0])
print(list(prices.values()))
print(list(prices.items()))

Output

['apple', 'bread', 'milk']
apple
[1.5, 0.8, 2.0]
[('apple', 1.5), ('bread', 0.8), ('milk', 2.0)]

3.2Calculating with the values

The built-in functions you know from lists work on values():

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
print(sum(grades.values()))
print(max(grades.values()))
print(min(grades.values()))
print(sum(grades.values()) / len(grades))

Output

255
92
78
85.0

Change it and run: add a fourth student with the grade 100. Which results change?

3.3Which key has the largest value?

max(grades) alone compares the keys (alphabetical order). To compare by value, give max a key function (as with max and key= in the lambda lesson):

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
print(max(grades))
print(max(grades, key=grades.get))
print(min(grades, key=grades.get))

Output

Murad
Murad
Leyla

Change it and run: change Leyla's grade to 99.

key=grades.get means: "for each name, compare the value that grades.get(name) gives".

3.4Sorting

sorted(dictionary) gives a sorted list of the keys:

Python
grades = {"Murad": 92, "Aylin": 85, "Leyla": 78}
print(sorted(grades))
print(sorted(grades.values()))
print(sorted(grades, key=grades.get, reverse=True))

Output

['Aylin', 'Leyla', 'Murad']
[78, 85, 92]
['Murad', 'Aylin', 'Leyla']

Change it and run: remove reverse=True.

The last line gives the names ordered from the highest grade to the lowest.

To sort the pairs by their value, sort items() and tell sorted to compare the second item of each pair. This is a small job for a lambda:

Python
grades = {"Murad": 92, "Aylin": 85, "Leyla": 78}
pairs = sorted(grades.items(), key=lambda pair: pair[1])
print(pairs)
for name, grade in pairs:
    print(name, grade)

Output

[('Leyla', 78), ('Aylin', 85), ('Murad', 92)]
Leyla 78
Aylin 85
Murad 92

Change it and run: add reverse=True to get the highest grade first.

3.5Keys are unique

A key can appear only once. If you write it twice, the last value wins:

Python
ages = {"Aylin": 20, "Murad": 25, "Aylin": 30}
print(ages)
print(len(ages))

Output

{'Aylin': 30, 'Murad': 25}
2

Values can repeat as often as you like:

Python
ages = {"Aylin": 20, "Murad": 20, "Leyla": 20}
print(ages)

Output

{'Aylin': 20, 'Murad': 20, 'Leyla': 20}

3.6Keys must be unchangeable (immutable)

Text, numbers and tuples can be keys. A list cannot, because a list can change:

Python
point_names = {(0, 0): "origin", (1, 2): "A"}
print(point_names[(1, 2)])

days = {1: "Monday", 2: "Tuesday"}
print(days[2])

Output

A
Tuesday
Python
wrong = {[1, 2]: "A"}

Error

TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

3.7Keys are case-sensitive

Python
student = {"name": "Aylin"}
print("name" in student)
print("Name" in student)

Output

True
False

3.8The order is kept

A dictionary remembers the order in which the pairs were added:

Python
order = {}
order["first"] = 1
order["second"] = 2
order["third"] = 3
print(order)

Output

{'first': 1, 'second': 2, 'third': 3}

3.9Copying and comparing

b = a does not copy a dictionary. As with lists, it gives the same dictionary a second name:

Python
a = {"x": 1}
b = a
b["y"] = 2
print(a)
print(b)

Output

{'x': 1, 'y': 2}
{'x': 1, 'y': 2}

Use .copy() for a real, separate copy:

Python
a = {"x": 1}
b = a.copy()
b["y"] = 2
print(a)
print(b)

Output

{'x': 1}
{'x': 1, 'y': 2}

Two dictionaries are equal when they have the same pairs. The order does not matter:

Python
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a == b)
print(a == {"x": 1})

Output

True
False

3.10All dictionary methods in one table

All dictionary methods in one table
MethodWhat it doesChanges the dictionary?Gives back
d[key]reads a valuenothe value (or KeyError)
d.get(key)reads a value safelynothe value or None
d.get(key, default)reads a value safelynothe value or the default
d[key] = valueadds or changes a pairyesnothing
d.update(other)adds or changes several pairsyesNone
d.setdefault(key, value)adds the pair only if the key is missingmaybethe value of the key
d.pop(key)removes a pairyesits value
d.popitem()removes the last pairyesthe pair as a tuple
del d[key]removes a pairyesnothing
d.clear()removes everythingyesNone
d.keys()all keysnothe keys
d.values()all valuesnothe values
d.items()all pairsnotuples (key, value)
d.copy()makes a separate copynoa new dictionary

Built-in functions that take a dictionary: len(d), list(d), sorted(d), max(d), min(d), key in d.

Try it yourself

From the dictionary prices, print how many products there are, the name of the cheapest product, and the product names in alphabetical order (a list). Three lines.
Show a hint
len(prices), then min(prices, key=prices.get), then sorted(prices).
Show the solution
Python
prices = {"milk": 2.0, "apple": 1.5, "bread": 0.8}
print(len(prices))
print(min(prices, key=prices.get))
print(sorted(prices))

Output

3
bread
['apple', 'bread', 'milk']

4Going through a dictionary with loops and if/else

4.1Looping over the keys

A for loop over a dictionary gives the keys:

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
for name in grades:
    print(name)

Output

Aylin
Murad
Leyla

With the key you can read the value:

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
for name in grades:
    print(name, grades[name])

Output

Aylin 85
Murad 92
Leyla 78

4.2Looping over the values

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
for grade in grades.values():
    print(grade)

Output

85
92
78

4.3Looping over the pairs: items()

items() gives tuples (key, value), and we unpack each one into two variables. This is the most common loop:

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
for name, grade in grades.items():
    print(name, "has", grade)

Output

Aylin has 85
Murad has 92
Leyla has 78

Change it and run: add a fourth student. The loop needs no change.

Looping over the pairs: items()
LoopYou getUse it when
for key in d:each keyyou need only the keys
for value in d.values():each valueyou need only the values
for key, value in d.items():each pairyou need both (most common)

4.4Loop + if/else: a label for every pair

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}
for name, grade in grades.items():
    if grade >= 50:
        print(name, "passed")
    else:
        print(name, "failed")

Output

Aylin passed
Murad failed
Leyla passed
Kamran failed

Change it and run: change the pass mark from 50 to 80.

4.5Loop + if: sum and count

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}
total = 0
passed = 0
for grade in grades.values():
    total = total + grade
    if grade >= 50:
        passed = passed + 1
print("Average:", total / len(grades))
print("Passed:", passed)

Output

Average: 58.75
Passed: 2

4.6Finding the best by hand

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
best_name = ""
best_grade = -1
for name, grade in grades.items():
    if grade > best_grade:
        best_name = name
        best_grade = grade
print(best_name, best_grade)

Output

Murad 92

Change it and run: change > to < and -1 to 101 to find the lowest grade.

(max(grades, key=grades.get) does the same job, but you should understand how it works.)

4.7Changing the values in a loop

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
for name in prices:
    prices[name] = prices[name] * 2
print(prices)

Output

{'apple': 3.0, 'bread': 1.6, 'milk': 4.0}

Change it and run: add 10% instead: multiply by 1.1.

Changing the values of existing keys in a loop is fine.

4.8Building a new dictionary with only some pairs

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}
passed = {}
for name, grade in grades.items():
    if grade >= 50:
        passed[name] = grade
print(passed)

Output

{'Aylin': 85, 'Leyla': 78}

Change it and run: keep the students who failed instead.

4.9The counting pattern (very important)

A dictionary is the best tool for counting how many times each thing appears. The key is the thing, the value is the count:

Python
votes = ["yes", "no", "yes", "yes", "no", "maybe"]
counts = {}
for vote in votes:
    if vote in counts:
        counts[vote] = counts[vote] + 1
    else:
        counts[vote] = 1
print(counts)

Output

{'yes': 3, 'no': 2, 'maybe': 1}

Change it and run: add two more "maybe" votes to the list.

Trace table:

The counting pattern (very important)
votealready in counts?counts after the step
yesno{'yes': 1}
nono{'yes': 1, 'no': 1}
yesyes{'yes': 2, 'no': 1}
yesyes{'yes': 3, 'no': 1}
noyes{'yes': 3, 'no': 2}
maybeno{'yes': 3, 'no': 2, 'maybe': 1}

With get and a default of 0, the if/else becomes one line:

Python
votes = ["yes", "no", "yes", "yes", "no", "maybe"]
counts = {}
for vote in votes:
    counts[vote] = counts.get(vote, 0) + 1
print(counts)

Output

{'yes': 3, 'no': 2, 'maybe': 1}

counts.get(vote, 0) means: "the count so far, or 0 if this is the first time".

The counting pattern: one step at a time

  1. 1votes = ["yes", "no", "yes"]
  2. 2counts = {}
  3. 3for vote in votes:
  4. 4 counts[vote] = counts.get(vote, 0) + 1
  5. 5print(counts)

What Python remembers

Nothing stored yet. Press “Run next line”.

Not started

Counting the letters of a word works in the same way, because a for loop can go through a text:

Python
word = "banana"
letters = {}
for letter in word:
    letters[letter] = letters.get(letter, 0) + 1
print(letters)

Output

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

Change it and run: count the letters of your own name.

4.10while with a dictionary

Python
stock = {"apple": 3, "bread": 1}
item = "apple"
while stock[item] > 0:
    stock[item] = stock[item] - 1
    print("Sold one", item, "- left:", stock[item])
print(stock)

Output

Sold one apple - left: 2
Sold one apple - left: 1
Sold one apple - left: 0
{'apple': 0, 'bread': 1}

Change it and run: start with 5 apples.

4.11Warning: do not add or remove keys while looping over a dictionary

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78}
for name in grades:
    if grades[name] < 50:
        del grades[name]

Error

RuntimeError: dictionary changed size during iteration

The safe way is to loop over a copy of the keys, made with list():

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78}
for name in list(grades):
    if grades[name] < 50:
        del grades[name]
print(grades)

Output

{'Aylin': 85, 'Leyla': 78}

Try it yourself

Given grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}, print the names of the students who failed (below 50), as a list.
Show a hint
Start with an empty list. Loop over grades.items() and append the name when the grade is below 50.
Show the solution
Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}
failed = []
for name, grade in grades.items():
    if grade < 50:
        failed.append(name)
print(failed)

Output

['Murad', 'Kamran']

5Nested data and building dictionaries

5.1A list as a value

Python
student = {"name": "Aylin", "grades": [85, 92, 78]}
print(student["grades"])
print(student["grades"][0])
print(sum(student["grades"]) / len(student["grades"]))

student["grades"].append(100)
print(student["grades"])

Output

[85, 92, 78]
85
85.0
[85, 92, 78, 100]

Change it and run: append one more grade and print the new average.

student["grades"] is a list, so everything from the last lesson works on it.

5.2A list of dictionaries

This is the most common way to store records (rows of a table). Every dictionary is one record with the same keys:

Python
students = [
    {"name": "Aylin", "grade": 85},
    {"name": "Murad", "grade": 92},
    {"name": "Leyla", "grade": 78},
]
print(students[0])
print(students[1]["name"])

for student in students:
    print(student["name"], student["grade"])

Output

{'name': 'Aylin', 'grade': 85}
Murad
Aylin 85
Murad 92
Leyla 78

Change it and run: add a fourth student record.

students[1] is the second dictionary, and students[1]["name"] is the value of its key "name".

5.3A dictionary inside a dictionary

Python
users = {
    "aylin": {"age": 20, "city": "Baku"},
    "murad": {"age": 25, "city": "Ganja"},
}
print(users["murad"])
print(users["murad"]["city"])

for username, info in users.items():
    print(username, "lives in", info["city"])

Output

{'age': 25, 'city': 'Ganja'}
Ganja
aylin lives in Baku
murad lives in Ganja

Change it and run: print Aylin's age.

5.4From two lists: zip

zip makes pairs from two lists, and dict turns the pairs into a dictionary:

Python
names = ["Aylin", "Murad", "Leyla"]
grades = [85, 92, 78]
result = dict(zip(names, grades))
print(result)

Output

{'Aylin': 85, 'Murad': 92, 'Leyla': 78}

The same job with a loop:

Python
names = ["Aylin", "Murad", "Leyla"]
grades = [85, 92, 78]
result = {}
for i in range(len(names)):
    result[names[i]] = grades[i]
print(result)

Output

{'Aylin': 85, 'Murad': 92, 'Leyla': 78}

5.5From the user

Each line has a name and a grade. split cuts the line, and we store the pair:

Python
n = int(input())
grades = {}
for i in range(n):
    name, grade = input().split()
    grades[name] = int(grade)
print(grades)

Output

2
Aylin 85
Murad 92
{'Aylin': 85, 'Murad': 92}

Change it and run: type your own names and grades.

Counting the words of a line typed by the user:

Python
words = input().split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

Output

red blue red green red blue
{'red': 3, 'blue': 2, 'green': 1}

Change it and run: type your own sentence.

Try it yourself

Given prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0} and cart = {"apple": 2, "milk": 3}, print the total price of the cart.
Show a hint
Loop over cart.items(). For every product, look up its price in prices and add price * amount to a total (solved problem 21).
Show the solution
Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
cart = {"apple": 2, "milk": 3}

total = 0
for product, amount in cart.items():
    total = total + prices[product] * amount
print(total)

Output

9.0

Try it yourself

Given students = [{"name": "Aylin", "grade": 85}, {"name": "Murad", "grade": 42}, {"name": "Leyla", "grade": 78}], print the average grade and the names of the students above the average. Print the average rounded to 1 decimal place after Average:, and the list of names after Above:.
Show a hint
Each item of the list is a dictionary: student["grade"]. First add up the grades for the average, then loop again and collect the names with a grade above it.
Show the solution
Python
students = [{"name": "Aylin", "grade": 85}, {"name": "Murad", "grade": 42}, {"name": "Leyla", "grade": 78}]

total = 0
for student in students:
    total = total + student["grade"]
average = total / len(students)
print("Average:", round(average, 1))

above = []
for student in students:
    if student["grade"] > average:
        above.append(student["name"])
print("Above:", above)

Output

Average: 68.3
Above: ['Aylin', 'Leyla']

6Sets

6.1Dictionaries so far (a short review before sets)

Dictionaries so far (a short review before sets)
PropertyDictionary
Written withcurly brackets and pairs: {"a": 1, "b": 2}
You find a value byits key
Keysunique, and unchangeable (text, numbers, tuples)
Mutable (changeable)yes: add, change, remove pairs
Orderthe order in which the pairs were added
Typical uselooking things up by name, counting, records

Now we meet the set. A set is like a dictionary that has only keys, no values.

6.2What is a set?

A set is a collection of unique values in no particular order. It has two special powers: it removes duplicates by itself, and it can be compared with other sets (what do they share, what is different).

Real-life picture: the guests of a party. A person is either on the guest list or not. Nobody is on it twice, and the list has no "first" or "second" guest.

6.3Creating sets

A set is written in curly brackets, with commas between the items and no colons:

Python
numbers = {3, 1, 2}
print(numbers)
print(type(numbers))
print(len(numbers))

Output

{1, 2, 3}
<class 'set'>
3

Duplicates disappear at once:

Python
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)
print(len(numbers))

Output

{1, 2, 3}
3

Change it and run: write more 1s into the set. The length stays 3.

6.4An empty set is set(), not {}

{} is an empty dictionary. An empty set is written set():

Python
a = {}
b = set()
print(type(a))
print(type(b))
print(len(b))

Output

<class 'dict'>
<class 'set'>
0

6.5Making a set from something else: set()

Python
print(set([1, 2, 2, 3, 1]))
print(set((5, 5, 6)))
print(sorted(set("banana")))

Output

{1, 2, 3}
{5, 6}
['a', 'b', 'n']

Change it and run: make a set from the letters of your name.

set() takes a list, a tuple or a text and keeps each value once.

A note about order: a set has no order, so the items of a set of texts can be printed in a different order each time you run the program. In this guide we use sorted(...) when we print a set of texts, so that the output is always the same. sorted gives a list.

Python
fruits = {"banana", "apple", "cherry"}
print(sorted(fruits))

Output

['apple', 'banana', 'cherry']

6.6A set has no indexes

Python
numbers = {10, 20, 30}
print(numbers[0])

Error

TypeError: 'set' object is not subscriptable

"Subscriptable" means "can be used with square brackets". A set cannot.

6.7Is it in the set? in

This is the question a set answers best, and it answers very fast, even with millions of items:

Python
allowed = {"admin", "editor", "owner"}
print("admin" in allowed)
print("guest" in allowed)
print("guest" not in allowed)

Output

True
False
True

6.8Items must be unchangeable

Numbers, text and tuples can be in a set. A list cannot:

Python
points = {(0, 0), (1, 2)}
print(len(points))

Output

2
Python
wrong = {[1, 2], [3, 4]}

Error

TypeError: cannot use 'list' as a set element (unhashable type: 'list')

6.9add(item): add one item

Python
numbers = {1, 2, 3}
numbers.add(4)
numbers.add(2)
print(numbers)

Output

{1, 2, 3, 4}

Change it and run: add 2 three more times.

Adding 2 again changes nothing, because 2 is already there.

6.10update(other): add several items

Python
numbers = {1, 2, 3}
numbers.update([3, 4, 5])
print(numbers)

Output

{1, 2, 3, 4, 5}

6.11remove(item) and discard(item)

Both remove an item. They differ only when the item is missing:

Python
numbers = {1, 2, 3}
numbers.remove(2)
print(numbers)
numbers.discard(3)
print(numbers)

Output

{1, 3}
{1}
Python
numbers = {1, 2, 3}
numbers.remove(10)

Error

KeyError: 10
Python
numbers = {1, 2, 3}
numbers.discard(10)
print(numbers)

Output

{1, 2, 3}

6.12pop() and clear()

pop() removes some item and gives it back. A set has no order, so you cannot choose which one. clear() removes everything.

Python
numbers = {1, 2, 3}
item = numbers.pop()
print(len(numbers))
numbers.clear()
print(numbers)
print(len(numbers))

Output

2
set()
0

An empty set is printed as set().

pop() and clear()
MethodWhat it doesItem is missing
s.add(x)adds one item
s.update(other)adds every item of other
s.remove(x)removes xKeyError
s.discard(x)removes xno error
s.pop()removes some item and gives it backKeyError if the set is empty
s.clear()removes everything

Try it yourself

Read a line of words. Print how many different words it has, and on the second line the different words in alphabetical order (a list).
Show a hint
set(words) keeps each word once. len(...) counts them and sorted(...) gives a list in order.
Show the solution
Python
words = input().split()
unique = set(words)
print(len(unique))
print(sorted(unique))

Output

3
['blue', 'green', 'red']

7Set operations, loops with sets, and choosing a structure

7.1Set operations

This is what makes sets special. Take two groups of students:

python_class = {"Aylin", "Murad", "Leyla", "Kamran"}
sql_class    = {"Leyla", "Kamran", "Nigar"}

7.2Union: in the first or in the second (or in both)

Python
python_class = {"Aylin", "Murad", "Leyla", "Kamran"}
sql_class = {"Leyla", "Kamran", "Nigar"}

print(sorted(python_class | sql_class))
print(sorted(python_class.union(sql_class)))

Output

['Aylin', 'Kamran', 'Leyla', 'Murad', 'Nigar']
['Aylin', 'Kamran', 'Leyla', 'Murad', 'Nigar']

7.3Intersection: in the first and in the second

Python
python_class = {"Aylin", "Murad", "Leyla", "Kamran"}
sql_class = {"Leyla", "Kamran", "Nigar"}

print(sorted(python_class & sql_class))
print(sorted(python_class.intersection(sql_class)))

Output

['Kamran', 'Leyla']
['Kamran', 'Leyla']

Change it and run: add "Nigar" to python_class.

7.4Difference: in the first but not in the second

Python
python_class = {"Aylin", "Murad", "Leyla", "Kamran"}
sql_class = {"Leyla", "Kamran", "Nigar"}

print(sorted(python_class - sql_class))
print(sorted(sql_class - python_class))
print(sorted(python_class.difference(sql_class)))

Output

['Aylin', 'Murad']
['Nigar']
['Aylin', 'Murad']

The order matters here: a - b and b - a are different.

7.5Symmetric difference: in exactly one of them

Python
python_class = {"Aylin", "Murad", "Leyla", "Kamran"}
sql_class = {"Leyla", "Kamran", "Nigar"}

print(sorted(python_class ^ sql_class))
print(sorted(python_class.symmetric_difference(sql_class)))

Output

['Aylin', 'Murad', 'Nigar']
['Aylin', 'Murad', 'Nigar']

7.6All four with numbers

Python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)
print(a & b)
print(a - b)
print(b - a)
print(a ^ b)

Output

{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{5, 6}
{1, 2, 5, 6}

Change it and run: change b to {4, 5, 6}.

All four with numbers
OperationOperatorMethodMeaning{1, 2, 3, 4} and {3, 4, 5, 6}
Uniona | ba.union(b)in a or in b{1, 2, 3, 4, 5, 6}
Intersectiona & ba.intersection(b)in both{3, 4}
Differencea - ba.difference(b)in a but not in b{1, 2}
Symmetric differencea ^ ba.symmetric_difference(b)in exactly one{1, 2, 5, 6}

The operators and the methods make a new set. a and b stay as they were.

Try it: set operations

a = {1, 2, 3, 4}   b = {3, 4, 5, 6}

>>> print(a & b)

{3, 4}

intersection: in both

7.7Comparing sets: subset, superset, disjoint

Python
small = {1, 2}
big = {1, 2, 3, 4}
other = {7, 8}

print(small.issubset(big))
print(small <= big)
print(big.issuperset(small))
print(small.isdisjoint(other))
print({1, 2} == {2, 1})

Output

True
True
True
True
True

Change it and run: add 9 to small. Which answers change?

  • small is a subset of big: every item of small is also in big.
  • big is a superset of small: it contains all of small.
  • Two sets are disjoint when they share nothing.
  • Two sets are equal when they have the same items. The order does not matter.

7.8for over a set

Python
numbers = {30, 10, 20}
for number in sorted(numbers):
    print(number)

Output

10
20
30

A set has no order, so we loop over sorted(numbers) when the order matters.

7.9Loop + if/else

Python
numbers = {4, 7, 10, 13}
for number in sorted(numbers):
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")

Output

4 is even
7 is odd
10 is even
13 is odd

7.10Loop + if: sum and count

Python
numbers = {3, 8, 5, 12, 7}
total = 0
count = 0
for number in numbers:
    if number % 2 == 1:
        total = total + number
        count = count + 1
print("Sum of odd numbers:", total)
print("How many:", count)

Output

Sum of odd numbers: 15
How many: 3

len, sum, min and max work on sets too:

Python
numbers = {3, 8, 5, 12, 7}
print(len(numbers), sum(numbers), min(numbers), max(numbers))

Output

5 35 3 12

7.11Removing duplicates from a list

Python
numbers = [3, 5, 3, 8, 5, 3, 9]
unique = set(numbers)
print(len(unique))
print(sorted(unique))

Output

4
[3, 5, 8, 9]

Change it and run: use your own list with repeated numbers.

set(numbers) removes the duplicates in one step. The original order is lost, so we sort the result.

7.12Has the list any duplicates?

Python
numbers = [3, 5, 3, 8]
if len(numbers) != len(set(numbers)):
    print("There are duplicates")
else:
    print("All values are different")

Output

There are duplicates

Change it and run: remove the second 3.

7.13Collecting what we have already seen

A set is the right place to remember values while a loop runs:

Python
numbers = [3, 5, 3, 8, 5, 9]
seen = set()
for number in numbers:
    if number in seen:
        print(number, "appears again")
    else:
        seen.add(number)

Output

3 appears again
5 appears again

7.14while with a set

Python
tasks = {"wash", "cook"}
while tasks:
    task = tasks.pop()
    print("Tasks left:", len(tasks))
print("All done")

Output

Tasks left: 1
Tasks left: 0
All done

An empty set counts as False, so while tasks: means "while the set is not empty".

7.15List, tuple, dictionary, set (the differences)

List, tuple, dictionary, set (the differences)
ListTupleDictionarySet
Brackets[1, 2](1, 2){"a": 1}{1, 2}
Empty[](){}set()
Orderedyesyesyes (order of adding)no
Find an item byindexindexkeynot possible, only in
Mutable (can change)yesnoyesyes
Duplicatesallowedallowedkeys unique, values may repeatnot possible
Typical useitems in order that changea fixed group of valueslooking up by name, countingunique values, comparing groups
Python
my_list = [1, 2, 2, 3]
my_tuple = (1, 2, 2, 3)
my_set = {1, 2, 2, 3}
my_dict = {"one": 1, "two": 2}

print(len(my_list), len(my_tuple), len(my_set), len(my_dict))
print(2 in my_list, 2 in my_tuple, 2 in my_set, "two" in my_dict)

Output

4 4 3 2
True True True True

How to choose:

  • The order matters, or you need positions: a list (or a tuple if it must not change).
  • You look things up by a name or an id, or you count things: a dictionary.
  • You only need to know "is it there?", or you want unique values, or you compare two groups: a set.

Converting between them:

Python
names = ["Aylin", "Murad", "Aylin"]
print(sorted(set(names)))
print(tuple(names))

grades = {"Aylin": 85, "Murad": 92}
print(list(grades))
print(list(grades.values()))
print(list(grades.items()))

Output

['Aylin', 'Murad']
('Aylin', 'Murad', 'Aylin')
['Aylin', 'Murad']
[85, 92]
[('Aylin', 85), ('Murad', 92)]

Try it yourself

Given two sets a = {1, 2, 3, 4} and b = {3, 4, 5}, print their union, intersection and difference a - b, each on its own line.
Show a hint
Three operators: |, & and -.
Show the solution
Python
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)

Output

{1, 2, 3, 4, 5}
{3, 4}
{1, 2}

8Comprehensions

8.1List comprehensions

A comprehension builds a new collection from another one in one line. You already know the long way.

8.2From a loop to a comprehension

The loop:

Python
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
    squares.append(n ** 2)
print(squares)

Output

[1, 4, 9, 16, 25]

The same thing as a list comprehension:

Python
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares)

Output

[1, 4, 9, 16, 25]

Change it and run: change n ** 2 to n * 10.

[expression for item in sequence]

Read it as: "give me n ** 2 for every n in numbers". The square brackets say that the result is a list.

From a loop to a comprehension
PartIn the loopIn the comprehension
What goes into the new listsquares.append(n ** 2)n ** 2 (written first)
Where the items come fromfor n in numbers:for n in numbers
The empty list at the startsquares = []not needed

More examples:

Python
print([n * 2 for n in range(5)])
print([word.upper() for word in ["red", "green", "blue"]])
print([len(word) for word in ["red", "green", "blue"]])
print([letter for letter in "abc"])

Output

[0, 2, 4, 6, 8]
['RED', 'GREEN', 'BLUE']
[3, 5, 4]
['a', 'b', 'c']

8.3A comprehension with a condition (choosing items)

An if at the end keeps only some items:

Python
numbers = [3, 8, 5, 12, 7, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)

Output

[8, 12, 10]

Change it and run: keep the numbers greater than 6.

This is the same as the loop:

Python
numbers = [3, 8, 5, 12, 7, 10]
evens = []
for n in numbers:
    if n % 2 == 0:
        evens.append(n)
print(evens)

Output

[8, 12, 10]
[expression for item in sequence if condition]

Choosing and changing together: the squares of the odd numbers.

Python
numbers = [1, 2, 3, 4, 5, 6]
print([n ** 2 for n in numbers if n % 2 == 1])

Output

[1, 9, 25]

Change it and run: make the cubes of the even numbers.

The loop: four lines

result = []
for n in numbers:
    if n % 2 == 1:
        result.append(n ** 2)

The comprehension: one line

result = [n ** 21 for n in numbers2 if n % 2 == 13]
  1. 1The expression: what goes into the new list. It is written first.
  2. 2The loop: where the items come from.
  3. 3The condition (optional): which items are kept.

8.4A comprehension with if/else (a different value for each item)

To give every item a value, with two possible results, the one-line if/else goes at the front:

Python
numbers = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)

Output

['odd', 'even', 'odd', 'even']
Python
grades = [85, 42, 78, 30]
print(["pass" if g >= 50 else "fail" for g in grades])

Output

['pass', 'fail', 'pass', 'fail']

Change it and run: change the pass mark to 80.

A comprehension with if/else (a different value for each item)
if at the endif/else at the front
Jobchooses itemschanges every item in one of two ways
Number of resultsthe same or feweralways the same
Example[n for n in numbers if n > 0][n if n > 0 else 0 for n in numbers]

8.5Comprehension, or map and filter?

They do the same jobs. A comprehension is usually easier to read, because it needs no lambda:

Python
numbers = [1, 2, 3, 4, 5, 6]

print(list(map(lambda n: n * 2, numbers)))
print([n * 2 for n in numbers])

print(list(filter(lambda n: n % 2 == 0, numbers)))
print([n for n in numbers if n % 2 == 0])

Output

[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 10, 12]
[2, 4, 6]
[2, 4, 6]
Comprehension, or map and filter?
Jobmap / filterComprehension
Change every itemlist(map(lambda n: n * 2, numbers))[n * 2 for n in numbers]
Choose itemslist(filter(lambda n: n > 0, numbers))[n for n in numbers if n > 0]
Bothmap around filter[n * 2 for n in numbers if n > 0]

Reading a list of numbers from the user with a comprehension:

Python
numbers = [int(piece) for piece in input().split()]
print(numbers)
print(sum(numbers))

Output

4 8 15
[4, 8, 15]
27

Change it and run: type your own numbers.

8.6Two loops in one comprehension

Python
pairs = [(x, y) for x in [1, 2] for y in ["a", "b"]]
print(pairs)

Output

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

The first for is the outer loop. Use this rarely: a normal nested loop is easier to read.

8.7Dictionary comprehension

Curly brackets and a key: value pair make a dictionary:

{key: value for item in sequence}
Python
numbers = [1, 2, 3, 4]
squares = {n: n ** 2 for n in numbers}
print(squares)

Output

{1: 1, 2: 4, 3: 9, 4: 16}

Change it and run: store the cube of each number.

The same thing as a loop:

Python
numbers = [1, 2, 3, 4]
squares = {}
for n in numbers:
    squares[n] = n ** 2
print(squares)

Output

{1: 1, 2: 4, 3: 9, 4: 16}

The length of every word:

Python
words = ["red", "green", "blue"]
lengths = {word: len(word) for word in words}
print(lengths)

Output

{'red': 3, 'green': 5, 'blue': 4}

From an existing dictionary, with items():

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
doubled = {name: price * 2 for name, price in prices.items()}
print(doubled)

Output

{'apple': 3.0, 'bread': 1.6, 'milk': 4.0}

Change it and run: take 10% off: multiply by 0.9.

With a condition:

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}
passed = {name: grade for name, grade in grades.items() if grade >= 50}
print(passed)

Output

{'Aylin': 85, 'Leyla': 78}

Change it and run: keep the students below 50.

Swapping keys and values:

Python
codes = {"AZ": "Azerbaijan", "TR": "Turkey"}
by_name = {country: code for code, country in codes.items()}
print(by_name)

Output

{'Azerbaijan': 'AZ', 'Turkey': 'TR'}

8.8Set comprehension

Curly brackets with a single value (no colon) make a set:

Python
numbers = [1, -1, 2, -2, 3]
print({n * n for n in numbers})

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
print(sorted({word[0] for word in words}))

Output

{1, 4, 9}
['a', 'b', 'c']

The squares of 1 and -1 are the same, so the set keeps the value once.

8.9Is there a tuple comprehension?

No. Round brackets do not make a tuple here. Wrap a comprehension in tuple():

Python
numbers = [1, 2, 3]
print(tuple(n * 2 for n in numbers))

Output

(2, 4, 6)
Is there a tuple comprehension?
KindBracketsExampleResult
List[ ][n * 2 for n in [1, 2, 3]][2, 4, 6]
Dictionary{ } with key: value{n: n * 2 for n in [1, 2, 3]}{1: 2, 2: 4, 3: 6}
Set{ } with one value{n % 2 for n in [1, 2, 3]}{0, 1}

8.10When not to use a comprehension

  • The body needs several steps, or prints something: write a loop.
  • The line becomes long or hard to read. A comprehension must fit in your head at one glance.
  • You do not need the new collection. A comprehension is for building something, not for repeating an action.

Both are correct. The loop is always a good answer.

Try it yourself

Read a list of numbers and print a list with only the even numbers. Use a list comprehension.
Show a hint
An if at the end chooses items: [n for n in numbers if n % 2 == 0].
Show the solution
Python
numbers = list(map(int, input().split()))
print([n for n in numbers if n % 2 == 0])

Output

[8, 12, 10]

Try it yourself

Read a list of words and print a dictionary with each word and its length. Use a dictionary comprehension.
Show a hint
The pattern is {key: value for word in words}. The key is the word, the value is len(word).
Show the solution
Python
words = input().split()
print({word: len(word) for word in words})

Output

{'red': 3, 'green': 5, 'blue': 4}

9Common mistakes

The red text is the real message Python shows. Where there is no message, the program runs but gives a wrong answer: the comment shows what it prints.

Reading a key that does not exist

Wrong

student = {"name": "Aylin", "age": 20}
print(student["email"])
KeyError: 'email'

Right

student = {"name": "Aylin", "age": 20}
print(student.get("email", "no email"))

# prints: no email

Use get, or check with in first.

Using a position: d[0]

Wrong

student = {"name": "Aylin", "age": 20}
print(student[0])
KeyError: 0

Right

student = {"name": "Aylin", "age": 20, "city": "Baku"}
print(student["name"])
print(student["age"])

# prints: Aylin, 20

A dictionary has keys, not positions.

Looking for a value with in

Wrong

grades = {"Aylin": 85, "Murad": 92}
print(85 in grades)

# prints: False

Right

grades = {"Aylin": 85, "Murad": 92}
print(85 in grades.values())

# prints: True

False, because in checks the keys. Use value in d.values().

{} for an empty set

Wrong

empty = {}
print(type(empty))

# prints: <class 'dict'>

Right

empty = set()
print(type(empty))

# prints: <class 'set'>

It is an empty dictionary. Write set().

Using an index on a set: s[0]

Wrong

numbers = {10, 20, 30}
print(numbers[0])
TypeError: 'set' object is not subscriptable

Right

numbers = {10, 20, 30}
print(sorted(numbers)[0])

# prints: 10

Loop over it, or use sorted(s)[0].

A list as a key or as a set item

Wrong

wrong = {[1, 2]: "A"}
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Right

names = {(1, 2): "A"}
print(names[(1, 2)])

# prints: A

Use a tuple.

The same key twice

Wrong

ages = {"Aylin": 20, "Murad": 25, "Aylin": 30}
print(ages)
print(len(ages))

# prints: {'Aylin': 30, 'Murad': 25}, 2

Right

ages = {"Aylin": 20, "Murad": 25, "Leyla": 30}
print(ages)
print(len(ages))

# prints: {'Aylin': 20, 'Murad': 25, 'Leyla': 30}, 3

The last value wins. Keys are unique.

b = a to copy a dictionary

Wrong

a = {"x": 1}
b = a
b["y"] = 2
print(a)
print(b)

# prints: {'x': 1, 'y': 2}, {'x': 1, 'y': 2}

Right

a = {"x": 1}
b = a.copy()
b["y"] = 2
print(a)
print(b)

# prints: {'x': 1}, {'x': 1, 'y': 2}

Both names change together. Use b = a.copy().

Removing keys while looping over the dictionary

Wrong

grades = {"Aylin": 85, "Murad": 42, "Leyla": 78}
for name in grades:
    if grades[name] < 50:
        del grades[name]
RuntimeError: dictionary changed size during iteration

Right

grades = {"Aylin": 85, "Murad": 42, "Leyla": 78}
for name in list(grades):
    if grades[name] < 50:
        del grades[name]
print(grades)

# prints: {'Aylin': 85, 'Leyla': 78}

Loop over list(d).

remove an item that is not in the set

Wrong

numbers = {1, 2, 3}
numbers.remove(10)
KeyError: 10

Right

numbers = {1, 2, 3}
numbers.discard(10)
print(numbers)

# prints: {1, 2, 3}

Use discard.

Expecting a set to keep the order

Wrong

numbers = {30, 10, 20}
print(numbers)

# prints: {10, 20, 30}

Right

numbers = [30, 10, 20]
print(numbers)

# prints: [30, 10, 20]

The order is not fixed. Use sorted(s), or a list.

counts[x] = counts[x] + 1 for a new key

Wrong

counts = {}
counts["yes"] = counts["yes"] + 1
KeyError: 'yes'

Right

counts = {}
counts["yes"] = counts.get("yes", 0) + 1
print(counts)

# prints: {'yes': 1}

Write counts[x] = counts.get(x, 0) + 1.

if at the wrong place in a comprehension

Wrong

numbers = [1, 2, 3]
labels = [n for n in numbers if n % 2 == 0 else "odd"]
SyntaxError: invalid syntax

Right

numbers = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)

# prints: ['odd', 'even', 'odd', 'even']

Choosing: if at the end. Two results: if/else at the front.

Forgetting .items() when looping over pairs

Wrong

grades = {"Aylin": 85, "Murad": 92}
for name, grade in grades:
    print(name, grade)
ValueError: too many values to unpack (expected 2)

Right

grades = {"Aylin": 85, "Murad": 92}
for name, grade in grades.items():
    print(name, grade)

# prints: Aylin 85, Murad 92

ValueError or wrong values. Write for key, value in d.items():.

Looking for a value with in:

Python
grades = {"Aylin": 85, "Murad": 92}
print(85 in grades)
print(85 in grades.values())

Output

False
True

Counting without get:

Python
counts = {}
counts["yes"] = counts["yes"] + 1

Error

KeyError: 'yes'

An if/else at the end of a comprehension:

Python
numbers = [1, 2, 3]
labels = [n for n in numbers if n % 2 == 0 else "odd"]

Error

SyntaxError: invalid syntax

10Solved problems (easy to medium-hard)

Every example was run, and the outputs are real.

10.1Level 1: Easy

Problem 1: A student card

Python
student = {"name": "Aylin", "age": 20, "city": "Baku"}
print("Name:", student["name"])
print("Age:", student["age"])
print("City:", student["city"])

Output

Name: Aylin
Age: 20
City: Baku

Problem 2: A safe lookup

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
product = input()
if product in prices:
    print(product, "costs", prices[product])
else:
    print(product, "is not in the shop")

Output

milk
milk costs 2.0

Change it and run: type kiwi.

Why: in checks the keys first, so prices[product] can never give a KeyError.

Problem 3: Add, change, remove

Python
stock = {"apple": 10, "bread": 4}
stock["milk"] = 6
stock["apple"] = stock["apple"] - 3
del stock["bread"]
print(stock)
print("Products:", len(stock))

Output

{'apple': 7, 'milk': 6}
Products: 2

Problem 4: The total price of a cart

Python
cart = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
total = 0
for price in cart.values():
    total = total + price
print("Total:", total)
print("Total:", sum(cart.values()))

Output

Total: 4.3
Total: 4.3

Why: the loop and sum(cart.values()) do the same job.

Problem 5: Print a price list

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
for name, price in prices.items():
    print(name, "-", price)

Output

apple - 1.5
bread - 0.8
milk - 2.0

Problem 6: How many different numbers?

Python
numbers = list(map(int, input().split()))
print(len(set(numbers)))

Output

3 5 3 8 5 3 9
4

Change it and run: type your own numbers.

Why: a set keeps each value once, so its length is the number of different values.

Problem 7: Common friends

Python
aylin_friends = {"Murad", "Leyla", "Nigar"}
kamran_friends = {"Leyla", "Nigar", "Elvin"}
print(sorted(aylin_friends & kamran_friends))

Output

['Leyla', 'Nigar']

Problem 8: Squares with a comprehension

Python
squares = [n ** 2 for n in range(1, 11)]
print(squares)

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Problem 9: Only the positive numbers

Python
numbers = [4, -2, 0, 7, -9, 3]
positive = [n for n in numbers if n > 0]
print(positive)

Output

[4, 7, 3]

10.2Level 2: Medium

Problem 10: Count the letters of a word

Python
word = "mississippi"
counts = {}
for letter in word:
    counts[letter] = counts.get(letter, 0) + 1
print(counts)

Output

{'m': 1, 'i': 4, 's': 4, 'p': 2}

Change it and run: count the letters of "banana".

Why: the counting pattern. get(letter, 0) gives 0 the first time a letter appears.

Problem 11: The most frequent word

Python
words = "the cat and the dog and the bird".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1

most = max(counts, key=counts.get)
print(counts)
print(most, counts[most])

Output

{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
the 3

Problem 12: The best and the worst student

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 78, "Kamran": 45}
best = max(grades, key=grades.get)
worst = min(grades, key=grades.get)
print("Best:", best, grades[best])
print("Worst:", worst, grades[worst])

Output

Best: Murad 92
Worst: Kamran 45

Problem 13: A grade letter for every student

Python
grades = {"Aylin": 85, "Murad": 92, "Leyla": 68, "Kamran": 45}
for name, grade in grades.items():
    if grade >= 90:
        letter = "A"
    elif grade >= 70:
        letter = "B"
    elif grade >= 50:
        letter = "C"
    else:
        letter = "F"
    print(name, letter)

Output

Aylin B
Murad A
Leyla C
Kamran F

Problem 14: Who passed? (loop and comprehension)

Python
grades = {"Aylin": 85, "Murad": 42, "Leyla": 78, "Kamran": 30}

passed = {}
for name, grade in grades.items():
    if grade >= 50:
        passed[name] = grade
print(passed)

print({name: grade for name, grade in grades.items() if grade >= 50})

Output

{'Aylin': 85, 'Leyla': 78}
{'Aylin': 85, 'Leyla': 78}

Problem 15: A dictionary from two lists

Python
products = ["apple", "bread", "milk"]
prices = [1.5, 0.8, 2.0]

by_loop = {}
for i in range(len(products)):
    by_loop[products[i]] = prices[i]
print(by_loop)

print(dict(zip(products, prices)))
print({products[i]: prices[i] for i in range(len(products))})

Output

{'apple': 1.5, 'bread': 0.8, 'milk': 2.0}
{'apple': 1.5, 'bread': 0.8, 'milk': 2.0}
{'apple': 1.5, 'bread': 0.8, 'milk': 2.0}

Problem 16: Students in only one class

Python
python_class = {"Aylin", "Murad", "Leyla", "Kamran"}
sql_class = {"Leyla", "Kamran", "Nigar"}

print("Both:", sorted(python_class & sql_class))
print("Only Python:", sorted(python_class - sql_class))
print("Only SQL:", sorted(sql_class - python_class))
print("Exactly one:", sorted(python_class ^ sql_class))
print("Everyone:", sorted(python_class | sql_class))

Output

Both: ['Kamran', 'Leyla']
Only Python: ['Aylin', 'Murad']
Only SQL: ['Nigar']
Exactly one: ['Aylin', 'Murad', 'Nigar']
Everyone: ['Aylin', 'Kamran', 'Leyla', 'Murad', 'Nigar']

Problem 17: Remove duplicates and keep the order

Python
numbers = [3, 5, 3, 8, 5, 3, 9]
seen = set()
unique = []
for number in numbers:
    if number not in seen:
        unique.append(number)
        seen.add(number)
print(unique)

Output

[3, 5, 8, 9]

Why: set(numbers) alone would lose the order. The list keeps the order, and the set answers "have I seen it?" quickly.

Problem 18: Even or odd label for every number

Python
numbers = [1, 2, 3, 4, 5]
labels = {n: "even" if n % 2 == 0 else "odd" for n in numbers}
print(labels)

Output

{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}

10.3Level 3: Medium-Hard

Problem 19: The average grade of every student

Python
students = {
    "Aylin": [85, 90, 78],
    "Murad": [92, 88],
    "Leyla": [60, 70, 80, 90],
}
for name, grades in students.items():
    print(name, round(sum(grades) / len(grades), 1))

averages = {name: round(sum(grades) / len(grades), 1) for name, grades in students.items()}
print(averages)

Output

Aylin 84.3
Murad 90.0
Leyla 75.0
{'Aylin': 84.3, 'Murad': 90.0, 'Leyla': 75.0}

Problem 20: Group words by their first letter

Python
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for word in words:
    first = word[0]
    if first not in groups:
        groups[first] = []
    groups[first].append(word)
print(groups)

Output

{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

Why: each value is a list. The first time a letter appears we create an empty list for it, then we append.

Problem 21: A shop bill

Python
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
cart = {"apple": 4, "milk": 2, "bread": 1}

total = 0
for product, amount in cart.items():
    cost = prices[product] * amount
    print(product, "x", amount, "=", cost)
    total = total + cost
print("Total:", total)

Output

apple x 4 = 6.0
milk x 2 = 4.0
bread x 1 = 0.8
Total: 10.8

Change it and run: buy 10 apples.

Why: two dictionaries with the same keys. The key from cart is used to look up the price.

Problem 22: The student with the highest grade in a list of records

Python
students = [
    {"name": "Aylin", "grade": 85},
    {"name": "Murad", "grade": 92},
    {"name": "Leyla", "grade": 78},
]

best = students[0]
for student in students:
    if student["grade"] > best["grade"]:
        best = student
print(best["name"], best["grade"])

print([student["name"] for student in students if student["grade"] >= 80])

Output

Murad 92
['Aylin', 'Murad']

Problem 23: Do two words use the same letters?

Python
first = "listen"
second = "silent"
print(set(first) == set(second))
print(sorted(set(first) - set("lint")))

Output

True
['e', 's']

Problem 24: Numbers that appear more than once

Python
numbers = [3, 5, 3, 8, 5, 3, 9]
counts = {}
for number in numbers:
    counts[number] = counts.get(number, 0) + 1

repeated = [number for number, count in counts.items() if count > 1]
print(counts)
print(repeated)

Output

{3: 3, 5: 2, 8: 1, 9: 1}
[3, 5]

Problem 25: Swap keys and values

Python
capitals = {"Azerbaijan": "Baku", "Turkey": "Ankara", "Georgia": "Tbilisi"}
countries = {city: country for country, city in capitals.items()}
print(countries)
print(countries["Baku"])

Output

{'Baku': 'Azerbaijan', 'Ankara': 'Turkey', 'Tbilisi': 'Georgia'}
Azerbaijan

Problem 26: Read grades, then answer questions

Python
n = int(input())
grades = {}
for i in range(n):
    name, grade = input().split()
    grades[name] = int(grade)

print("Students:", len(grades))
print("Average:", sum(grades.values()) / len(grades))
print("Passed:", [name for name, grade in grades.items() if grade >= 50])
print("Best:", max(grades, key=grades.get))

Output

3
Aylin 85
Murad 42
Leyla 78
Students: 3
Average: 68.33333333333333
Passed: ['Aylin', 'Leyla']
Best: Aylin

Change it and run: type your own students.

Why: build the dictionary from the input first, then each question is one short line.

11Practice problems (try them yourself)

Fifteen problems in three levels. The first lines in each editor read the input or give the starting values. Press Run to try one input, then Check to run your code with several inputs.

Easy

Reading and changing a dictionary, unique values, a first comprehension.

  1. 1.Given prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}, read a product name and print its price, or not found if it is not in the dictionary.Examples: milk gives 2.0apple gives 1.5bread gives 0.8
    Show a hint
    One method does both jobs: prices.get(product, "not found"). An if product in prices: with else works too.
    Show one possible solution
    Python
    prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}
    product = input()
    print(prices.get(product, "not found"))

    Output

    2.0
  2. 2.Given stock = {"apple": 10, "bread": 4}, add "milk" with 6, increase "apple" by 5, remove "bread", and print the dictionary.
    Show a hint
    Adding and changing both use stock[key] = value. Remove with del stock["bread"] or stock.pop("bread").
    Show one possible solution
    Python
    stock = {"apple": 10, "bread": 4}
    stock["milk"] = 6
    stock["apple"] = stock["apple"] + 5
    del stock["bread"]
    print(stock)

    Output

    {'apple': 15, 'milk': 6}
  3. 3.Given grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}, print the average grade.
    Show a hint
    The grades are the values: sum(grades.values()) divided by len(grades).
    Show one possible solution
    Python
    grades = {"Aylin": 85, "Murad": 92, "Leyla": 78}
    print(sum(grades.values()) / len(grades))

    Output

    85.0
  4. 4.Read a list of numbers and print how many different numbers it has.Examples: 3 5 3 8 5 3 9 gives 41 1 1 gives 14 gives 1
    Show a hint
    A set keeps each value once: len(set(numbers)).
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print(len(set(numbers)))

    Output

    4
  5. 5.Read a list of numbers and print a list with every number multiplied by 3. Use a list comprehension.Examples: 1 2 3 gives [3, 6, 9]0 gives [0]-4 5 gives [-12, 15]
    Show a hint
    The pattern is [expression for n in numbers]. The expression here is n * 3.
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print([n * 3 for n in numbers])

    Output

    [3, 6, 9]

Medium

Counting, set operations and a function.

  1. 6.Read a line of words and print how many times each word appears, as a dictionary.Examples: red blue red green red blue gives {'red': 3, 'blue': 2, 'green': 1}a gives {'a': 1}x y x y gives {'x': 2, 'y': 2}
    Show a hint
    The counting pattern: start with counts = {}, and for every word write counts[word] = counts.get(word, 0) + 1.
    Show one possible solution
    Python
    words = input().split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    print(counts)

    Output

    {'red': 3, 'blue': 2, 'green': 1}
  2. 7.Read a word and print the letter that appears most often. If several letters share the top count, print the one that appears first in the word.Examples: banana gives amississippi gives ia gives a
    Show a hint
    Count the letters with the counting pattern. Then max(counts, key=counts.get) gives the key with the largest value (the first one when several are equal).
    Show one possible solution
    Python
    word = input()
    counts = {}
    for letter in word:
        counts[letter] = counts.get(letter, 0) + 1
    print(max(counts, key=counts.get))

    Output

    a
  3. 8.Read two lines of numbers and print the numbers that appear in both lines, sorted. Print them as a list.Examples: 1 2 3 4, 3 4 5 gives [3, 4]1 2, 3 4 gives []5 5 5, 5 gives [5]
    Show a hint
    Turn both lists into sets and take the intersection: set(a) & set(b). sorted(...) gives a list in order.
    Show one possible solution
    Python
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    print(sorted(set(a) & set(b)))

    Output

    [3, 4]
  4. 9.Write a function count_values(numbers) that returns a dictionary with how many times each number appears.Examples: 3 5 3 8 5 3 gives {3: 3, 5: 2, 8: 1}1 gives {1: 1}2 2 2 gives {2: 3}
    Show a hint
    The counting pattern inside a function. Build the dictionary in a loop and return it at the end.
    Show one possible solution
    Python
    def count_values(numbers):
        counts = {}
        for number in numbers:
            counts[number] = counts.get(number, 0) + 1
        return counts
    
    numbers = list(map(int, input().split()))
    print(count_values(numbers))

    Output

    {3: 3, 5: 2, 8: 1}
  5. 10.Read a list of numbers and print True if all the numbers are different, otherwise False.Examples: 1 2 3 gives True1 2 1 gives False5 gives True
    Show a hint
    If nothing repeats, the set has as many items as the list: compare len(numbers) with len(set(numbers)).
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print(len(numbers) == len(set(numbers)))

    Output

    True

Medium-Hard

Several steps together: counting, grouping, input and comprehensions.

  1. 11.Read a list of numbers and print the numbers that appear exactly once, in their original order, as a list.Examples: 3 5 3 8 5 9 gives [8, 9]1 1 2 2 gives []7 gives [7]
    Show a hint
    First count every number in a dictionary. Then go through the list again and keep the numbers whose count is 1 (a loop with if, or a comprehension).
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    counts = {}
    for number in numbers:
        counts[number] = counts.get(number, 0) + 1
    print([number for number in numbers if counts[number] == 1])

    Output

    [8, 9]
  2. 12.Read two lines of words and print the words that are in the first line but not in the second, sorted. Print them as a list.Examples: red blue green, blue gives ['green', 'red']a b, a b gives []x, y gives ['x']
    Show a hint
    The difference of two sets: set(first) - set(second). Sort the result.
    Show one possible solution
    Python
    first = input().split()
    second = input().split()
    print(sorted(set(first) - set(second)))

    Output

    ['green', 'red']
  3. 13.Read n, then n lines with a name and a grade. Print the name of the student with the highest grade. If several students share the highest grade, print the first of them.Examples: 3, Aylin 85, Murad 92, Leyla 78 gives Murad1, Kamran 45 gives Kamran2, Ali 70, Veli 70 gives Ali
    Show a hint
    The dictionary is already built by the first lines. max(grades, key=grades.get) gives the name with the largest grade.
    Show one possible solution
    Python
    n = int(input())
    grades = {}
    for i in range(n):
        name, grade = input().split()
        grades[name] = int(grade)
    print(max(grades, key=grades.get))

    Output

    Murad
  4. 14.Read a line of words and print a dictionary that groups the words by their length. Example: red blue sky green gives {3: ['red', 'sky'], 4: ['blue'], 5: ['green']}.Examples: red blue sky green gives {3: ['red', 'sky'], 4: ['blue'], 5: ['green']}a bb cc d gives {1: ['a', 'd'], 2: ['bb', 'cc']}hello gives {5: ['hello']}
    Show a hint
    Each value is a list. When a length appears for the first time, store an empty list for it, then append the word (solved problem 20 groups by the first letter in the same way).
    Show one possible solution
    Python
    words = input().split()
    groups = {}
    for word in words:
        length = len(word)
        if length not in groups:
            groups[length] = []
        groups[length].append(word)
    print(groups)

    Output

    {3: ['red', 'sky'], 4: ['blue'], 5: ['green']}
  5. 15.Read a list of numbers and print a dictionary where each number is a key and the value is "even" or "odd". Use a dictionary comprehension.Examples: 1 2 3 gives {1: 'odd', 2: 'even', 3: 'odd'}4 gives {4: 'even'}0 7 gives {0: 'even', 7: 'odd'}
    Show a hint
    The pattern is {key: value for n in numbers}. The value is the one-line if/else: "even" if n % 2 == 0 else "odd".
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print({n: "even" if n % 2 == 0 else "odd" for n in numbers})

    Output

    {1: 'odd', 2: 'even', 3: 'odd'}

12Check yourself

Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.

Question 1

1.What does this print?

student = {"name": "Aylin", "age": 20}
print(student.get("city", "unknown"))

Question 2

2.What does this print?

d = {"a": 1}
d["b"] = 2
d["a"] = 5
print(len(d), d["a"])

Question 3

3.What does this print?

grades = {"Aylin": 85, "Murad": 92}
print("Murad" in grades, 92 in grades)

Question 4

4.What does this print?

ages = {"Aylin": 20, "Murad": 25, "Aylin": 30}
print(len(ages), ages["Aylin"])

Question 5

5.What does this print?

counts = {}
for letter in "hello":
    counts[letter] = counts.get(letter, 0) + 1
print(counts["l"], len(counts))

Question 6

6.What does this print?

grades = {"Aylin": 85, "Murad": 92}
for x in grades:
    print(x, end=" ")

Question 7

7.Which line creates an empty set?

Question 8

8.What does this print?

print(len({1, 2, 2, 3, 3, 3}))

Question 9

9.What does this print?

a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a & b, a - b)

Question 10

10.What does this print?

print([n * 2 for n in [1, 2, 3] if n > 1])

Question 11

11.What does this print?

print({n: n * n for n in [1, 2, 3]})

Question 12

12.What does this print?

print(["big" if n > 2 else "small" for n in [1, 2, 3]])

0 of 12 answered.

13Quick summary

Quick summary
ConceptWhat it doesExample
Dictionarypairs of key and value{"a": 1, "b": 2}
Read a valueby keyd["a"], d.get("a", 0)
Add or changeby keyd["c"] = 3, d.update({...})
Removeby keyd.pop("a"), del d["a"]
keys / values / itemsall keys, values, pairsfor k, v in d.items():
inis the key there?"a" in d
Counting patternhow many times each thing appearsd[x] = d.get(x, 0) + 1
Setunique values, no order{1, 2, 3}, set()
add / remove / discardchange a sets.add(4)
Union / intersectionor / anda | b, a & b
Difference / symmetric differenceonly in a / in exactly onea - b, a ^ b
Unique valuesremove duplicatesset(numbers)
List comprehensiona new list in one line[n * 2 for n in numbers]
With a conditionchoose items[n for n in numbers if n > 0]
With if/elseone of two values for every item["even" if n % 2 == 0 else "odd" for n in numbers]
Dictionary comprehensiona new dictionary in one line{n: n ** 2 for n in numbers}
Set comprehensiona new set in one line{n % 2 for n in numbers}