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
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 26 solved problems, ready to run and change.
topic-05-dictionaries-sets-comprehensions.ipynb, 89 KB
Practice notebook
The 15 practice problems with examples of input and output, a hint and a hidden solution for each.
topic-05-practice.ipynb, 27 KB
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.What a dictionary is, and how to create, read, change, grow and shrink one
- 2.Every common dictionary method and when to use it
- 3.How to go through a dictionary with loops and
if/else, and the counting pattern - 4.Dictionaries inside lists and lists inside dictionaries
- 5.What a set is, and how to add and remove items
- 6.Set operations: union, intersection, difference, symmetric difference, subset
- 7.How list, tuple, dictionary and set differ, and when to use each
- 8.List, dictionary and set comprehensions, with and without a condition
- 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:
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:
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.
| List | Dictionary | |
|---|---|---|
| You find a value by | its position (index): grades[1] | its key: grades["Murad"] |
| Written with | [ ] | { } with key: value pairs |
A list: each value has a position
grades[1] gives 92
A dictionary: each value has a key
grades["Murad"] gives 92
1.2Creating dictionaries
A dictionary is written in curly brackets. Each item is a pair key: value, and the pairs are separated by commas:
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:
student = {
"name": "Aylin",
"age": 20,
"city": "Baku",
}
print(student)Output
{'name': 'Aylin', 'age': 20, 'city': 'Baku'}1.3How many pairs? len()
student = {"name": "Aylin", "age": 20, "city": "Baku"}
print(len(student))
print(len({}))Output
3 0
1.4Making a dictionary with dict()
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]
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:
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.
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:
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:
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:
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.
| Way | Key exists | Key is missing |
|---|---|---|
d[key] | the value | KeyError |
d.get(key) | the value | None |
d.get(key, default) | the value | the default |
key in d | True | False |
Try it yourself
Show a hint
print(me["name"]).Show the solution
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.
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:
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:
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
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
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.
| Way | Key exists | Key is missing |
|---|---|---|
d[key] = value | changes the value | adds the pair |
d.update({...}) | changes the values | adds the pairs |
d.setdefault(key, value) | does nothing | adds the pair |
2.5pop(key): remove a pair and give its value back
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:
student = {"name": "Aylin"}
student.pop("email")Error
KeyError: 'email'
student = {"name": "Aylin"}
print(student.pop("email", "nothing to remove"))Output
nothing to remove
2.6del: delete a pair
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
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
student = {"name": "Aylin", "age": 20}
student.clear()
print(student)
print(len(student))Output
{}
0| Tool | Removes | Gives back | Missing key |
|---|---|---|---|
d.pop(key) | that pair | the value | KeyError |
d.pop(key, default) | that pair | the value, or the default | no error |
del d[key] | that pair | nothing | KeyError |
d.popitem() | the last pair | the pair as a tuple | KeyError if the dictionary is empty |
d.clear() | everything | nothing | no error |
Press a line and watch what happens to the dictionary.
student = {"name": "Aylin", "age": 20}Filled boxes are keys, outlined boxes are values.
Try it yourself
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
profile[key] = value. removed = profile.pop("name") removes the pair and stores its value.Show the solution
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()
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):
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():
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):
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:
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:
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 92Change 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:
ages = {"Aylin": 20, "Murad": 25, "Aylin": 30}
print(ages)
print(len(ages))Output
{'Aylin': 30, 'Murad': 25}
2Values can repeat as often as you like:
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:
point_names = {(0, 0): "origin", (1, 2): "A"}
print(point_names[(1, 2)])
days = {1: "Monday", 2: "Tuesday"}
print(days[2])Output
A Tuesday
wrong = {[1, 2]: "A"}Error
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
3.7Keys are case-sensitive
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:
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:
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:
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:
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
| Method | What it does | Changes the dictionary? | Gives back |
|---|---|---|---|
d[key] | reads a value | no | the value (or KeyError) |
d.get(key) | reads a value safely | no | the value or None |
d.get(key, default) | reads a value safely | no | the value or the default |
d[key] = value | adds or changes a pair | yes | nothing |
d.update(other) | adds or changes several pairs | yes | None |
d.setdefault(key, value) | adds the pair only if the key is missing | maybe | the value of the key |
d.pop(key) | removes a pair | yes | its value |
d.popitem() | removes the last pair | yes | the pair as a tuple |
del d[key] | removes a pair | yes | nothing |
d.clear() | removes everything | yes | None |
d.keys() | all keys | no | the keys |
d.values() | all values | no | the values |
d.items() | all pairs | no | tuples (key, value) |
d.copy() | makes a separate copy | no | a 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
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
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:
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:
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
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:
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.
| Loop | You get | Use it when |
|---|---|---|
for key in d: | each key | you need only the keys |
for value in d.values(): | each value | you need only the values |
for key, value in d.items(): | each pair | you need both (most common) |
4.4Loop + if/else: a label for every pair
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
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
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
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
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:
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:
| vote | already in counts? | counts after the step |
|---|---|---|
| yes | no | {'yes': 1} |
| no | no | {'yes': 1, 'no': 1} |
| yes | yes | {'yes': 2, 'no': 1} |
| yes | yes | {'yes': 3, 'no': 1} |
| no | yes | {'yes': 3, 'no': 2} |
| maybe | no | {'yes': 3, 'no': 2, 'maybe': 1} |
With get and a default of 0, the if/else becomes one line:
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
- 1votes = ["yes", "no", "yes"]
- 2counts = {}
- 3for vote in votes:
- 4 counts[vote] = counts.get(vote, 0) + 1
- 5print(counts)
What Python remembers
Nothing stored yet. Press “Run next line”.
Counting the letters of a word works in the same way, because a for loop can go through a text:
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
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
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():
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
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
grades.items() and append the name when the grade is below 50.Show the solution
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
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:
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 78Change 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
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 GanjaChange 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:
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:
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:
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:
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
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
cart.items(). For every product, look up its price in prices and add price * amount to a total (solved problem 21).Show the solution
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
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
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
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)
| Property | Dictionary |
|---|---|
| Written with | curly brackets and pairs: {"a": 1, "b": 2} |
| You find a value by | its key |
| Keys | unique, and unchangeable (text, numbers, tuples) |
| Mutable (changeable) | yes: add, change, remove pairs |
| Order | the order in which the pairs were added |
| Typical use | looking 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:
numbers = {3, 1, 2}
print(numbers)
print(type(numbers))
print(len(numbers))Output
{1, 2, 3}
<class 'set'>
3Duplicates disappear at once:
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)
print(len(numbers))Output
{1, 2, 3}
3Change 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():
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()
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.
fruits = {"banana", "apple", "cherry"}
print(sorted(fruits))Output
['apple', 'banana', 'cherry']
6.6A set has no indexes
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:
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:
points = {(0, 0), (1, 2)}
print(len(points))Output
2
wrong = {[1, 2], [3, 4]}Error
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
6.9add(item): add one item
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
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:
numbers = {1, 2, 3}
numbers.remove(2)
print(numbers)
numbers.discard(3)
print(numbers)Output
{1, 3}
{1}numbers = {1, 2, 3}
numbers.remove(10)Error
KeyError: 10
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.
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().
| Method | What it does | Item is missing |
|---|---|---|
s.add(x) | adds one item | |
s.update(other) | adds every item of other | |
s.remove(x) | removes x | KeyError |
s.discard(x) | removes x | no error |
s.pop() | removes some item and gives it back | KeyError if the set is empty |
s.clear() | removes everything |
Try it yourself
Show a hint
set(words) keeps each word once. len(...) counts them and sorted(...) gives a list in order.Show the solution
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_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_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_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_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
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}.
| Operation | Operator | Method | Meaning | {1, 2, 3, 4} and {3, 4, 5, 6} |
|---|---|---|---|---|
| Union | a | b | a.union(b) | in a or in b | {1, 2, 3, 4, 5, 6} |
| Intersection | a & b | a.intersection(b) | in both | {3, 4} |
| Difference | a - b | a.difference(b) | in a but not in b | {1, 2} |
| Symmetric difference | a ^ b | a.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
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?
smallis a subset ofbig: every item ofsmallis also inbig.bigis a superset ofsmall: it contains all ofsmall.- 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
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
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
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:
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
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?
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:
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
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 | |
|---|---|---|---|---|
| Brackets | [1, 2] | (1, 2) | {"a": 1} | {1, 2} |
| Empty | [] | () | {} | set() |
| Ordered | yes | yes | yes (order of adding) | no |
| Find an item by | index | index | key | not possible, only in |
| Mutable (can change) | yes | no | yes | yes |
| Duplicates | allowed | allowed | keys unique, values may repeat | not possible |
| Typical use | items in order that change | a fixed group of values | looking up by name, counting | unique values, comparing groups |
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:
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
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
|, & and -.Show the solution
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:
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:
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.
| Part | In the loop | In the comprehension |
|---|---|---|
| What goes into the new list | squares.append(n ** 2) | n ** 2 (written first) |
| Where the items come from | for n in numbers: | for n in numbers |
| The empty list at the start | squares = [] | not needed |
More examples:
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:
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:
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.
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]
- 1The expression: what goes into the new list. It is written first.
- 2The loop: where the items come from.
- 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:
numbers = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)Output
['odd', 'even', 'odd', 'even']
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.
| if at the end | if/else at the front | |
|---|---|---|
| Job | chooses items | changes every item in one of two ways |
| Number of results | the same or fewer | always 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:
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]
| Job | map / filter | Comprehension |
|---|---|---|
| Change every item | list(map(lambda n: n * 2, numbers)) | [n * 2 for n in numbers] |
| Choose items | list(filter(lambda n: n > 0, numbers)) | [n for n in numbers if n > 0] |
| Both | map around filter | [n * 2 for n in numbers if n > 0] |
Reading a list of numbers from the user with a comprehension:
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
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}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:
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:
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():
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:
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:
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:
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():
numbers = [1, 2, 3]
print(tuple(n * 2 for n in numbers))Output
(2, 4, 6)
| Kind | Brackets | Example | Result |
|---|---|---|---|
| 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
Show a hint
if at the end chooses items: [n for n in numbers if n % 2 == 0].Show the solution
numbers = list(map(int, input().split()))
print([n for n in numbers if n % 2 == 0])Output
[8, 12, 10]
Try it yourself
Show a hint
{key: value for word in words}. The key is the word, the value is len(word).Show the solution
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 emailUse 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, 20A dictionary has keys, not positions.
Looking for a value with in
Wrong
grades = {"Aylin": 85, "Murad": 92}
print(85 in grades)
# prints: FalseRight
grades = {"Aylin": 85, "Murad": 92}
print(85 in grades.values())
# prints: TrueFalse, 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: 10Loop 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: AUse a tuple.
The same key twice
Wrong
ages = {"Aylin": 20, "Murad": 25, "Aylin": 30}
print(ages)
print(len(ages))
# prints: {'Aylin': 30, 'Murad': 25}, 2Right
ages = {"Aylin": 20, "Murad": 25, "Leyla": 30}
print(ages)
print(len(ages))
# prints: {'Aylin': 20, 'Murad': 25, 'Leyla': 30}, 3The 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"] + 1KeyError: '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 92ValueError or wrong values. Write for key, value in d.items():.
Looking for a value with in:
grades = {"Aylin": 85, "Murad": 92}
print(85 in grades)
print(85 in grades.values())Output
False True
Counting without get:
counts = {}
counts["yes"] = counts["yes"] + 1Error
KeyError: 'yes'
An if/else at the end of a comprehension:
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
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
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
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: 2Problem 4: The total price of a cart
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
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?
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
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
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
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
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
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 3Problem 12: The best and the worst student
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
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)
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
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_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
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
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
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
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
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
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?
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
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
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'}
AzerbaijanProblem 26: Read grades, then answer questions
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.Given
prices = {"apple": 1.5, "bread": 0.8, "milk": 2.0}, read a product name and print its price, ornot foundif it is not in the dictionary.Examples:milkgives2.0applegives1.5breadgives0.8Show a hint
One method does both jobs:prices.get(product, "not found"). Anif product in prices:withelseworks too.Show one possible solution
Pythonprices = {"apple": 1.5, "bread": 0.8, "milk": 2.0} product = input() print(prices.get(product, "not found"))Output
2.0
- 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 usestock[key] = value. Remove withdel stock["bread"]orstock.pop("bread").Show one possible solution
Pythonstock = {"apple": 10, "bread": 4} stock["milk"] = 6 stock["apple"] = stock["apple"] + 5 del stock["bread"] print(stock)Output
{'apple': 15, 'milk': 6} - 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 bylen(grades).Show one possible solution
Pythongrades = {"Aylin": 85, "Murad": 92, "Leyla": 78} print(sum(grades.values()) / len(grades))Output
85.0
- 4.Read a list of numbers and print how many different numbers it has.Examples:
3 5 3 8 5 3 9gives41 1 1gives14gives1Show a hint
A set keeps each value once:len(set(numbers)).Show one possible solution
Pythonnumbers = list(map(int, input().split())) print(len(set(numbers)))Output
4
- 5.Read a list of numbers and print a list with every number multiplied by 3. Use a list comprehension.Examples:
1 2 3gives[3, 6, 9]0gives[0]-4 5gives[-12, 15]Show a hint
The pattern is[expression for n in numbers]. The expression here isn * 3.Show one possible solution
Pythonnumbers = list(map(int, input().split())) print([n * 3 for n in numbers])Output
[3, 6, 9]
Medium
Counting, set operations and a function.
- 6.Read a line of words and print how many times each word appears, as a dictionary.Examples:
red blue red green red bluegives{'red': 3, 'blue': 2, 'green': 1}agives{'a': 1}x y x ygives{'x': 2, 'y': 2}Show a hint
The counting pattern: start withcounts = {}, and for every word writecounts[word] = counts.get(word, 0) + 1.Show one possible solution
Pythonwords = input().split() counts = {} for word in words: counts[word] = counts.get(word, 0) + 1 print(counts)Output
{'red': 3, 'blue': 2, 'green': 1} - 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:
bananagivesamississippigivesiagivesaShow a hint
Count the letters with the counting pattern. Thenmax(counts, key=counts.get)gives the key with the largest value (the first one when several are equal).Show one possible solution
Pythonword = input() counts = {} for letter in word: counts[letter] = counts.get(letter, 0) + 1 print(max(counts, key=counts.get))Output
a
- 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 5gives[3, 4]1 2, 3 4gives[]5 5 5, 5gives[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
Pythona = list(map(int, input().split())) b = list(map(int, input().split())) print(sorted(set(a) & set(b)))Output
[3, 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 3gives{3: 3, 5: 2, 8: 1}1gives{1: 1}2 2 2gives{2: 3}Show a hint
The counting pattern inside a function. Build the dictionary in a loop andreturnit at the end.Show one possible solution
Pythondef 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} - 10.Read a list of numbers and print
Trueif all the numbers are different, otherwiseFalse.Examples:1 2 3givesTrue1 2 1givesFalse5givesTrueShow a hint
If nothing repeats, the set has as many items as the list: comparelen(numbers)withlen(set(numbers)).Show one possible solution
Pythonnumbers = list(map(int, input().split())) print(len(numbers) == len(set(numbers)))Output
True
Medium-Hard
Several steps together: counting, grouping, input and comprehensions.
- 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 9gives[8, 9]1 1 2 2gives[]7gives[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 withif, or a comprehension).Show one possible solution
Pythonnumbers = 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]
- 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, bluegives['green', 'red']a b, a bgives[]x, ygives['x']Show a hint
The difference of two sets:set(first) - set(second). Sort the result.Show one possible solution
Pythonfirst = input().split() second = input().split() print(sorted(set(first) - set(second)))Output
['green', 'red']
- 13.Read
n, thennlines 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 78givesMurad1, Kamran 45givesKamran2, Ali 70, Veli 70givesAliShow 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
Pythonn = int(input()) grades = {} for i in range(n): name, grade = input().split() grades[name] = int(grade) print(max(grades, key=grades.get))Output
Murad
- 14.Read a line of words and print a dictionary that groups the words by their length. Example:
red blue sky greengives{3: ['red', 'sky'], 4: ['blue'], 5: ['green']}.Examples:red blue sky greengives{3: ['red', 'sky'], 4: ['blue'], 5: ['green']}a bb cc dgives{1: ['a', 'd'], 2: ['bb', 'cc']}hellogives{5: ['hello']}Show a hint
Each value is a list. When a length appears for the first time, store an empty list for it, thenappendthe word (solved problem 20 groups by the first letter in the same way).Show one possible solution
Pythonwords = 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']} - 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 3gives{1: 'odd', 2: 'even', 3: 'odd'}4gives{4: 'even'}0 7gives{0: 'even', 7: 'odd'}Show a hint
The pattern is{key: value for n in numbers}. The value is the one-lineif/else:"even" if n % 2 == 0 else "odd".Show one possible solution
Pythonnumbers = 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.
0 of 12 answered.
13Quick summary
| Concept | What it does | Example |
|---|---|---|
| Dictionary | pairs of key and value | {"a": 1, "b": 2} |
| Read a value | by key | d["a"], d.get("a", 0) |
| Add or change | by key | d["c"] = 3, d.update({...}) |
| Remove | by key | d.pop("a"), del d["a"] |
keys / values / items | all keys, values, pairs | for k, v in d.items(): |
in | is the key there? | "a" in d |
| Counting pattern | how many times each thing appears | d[x] = d.get(x, 0) + 1 |
| Set | unique values, no order | {1, 2, 3}, set() |
add / remove / discard | change a set | s.add(4) |
| Union / intersection | or / and | a | b, a & b |
| Difference / symmetric difference | only in a / in exactly one | a - b, a ^ b |
| Unique values | remove duplicates | set(numbers) |
| List comprehension | a new list in one line | [n * 2 for n in numbers] |
| With a condition | choose items | [n for n in numbers if n > 0] |
With if/else | one of two values for every item | ["even" if n % 2 == 0 else "odd" for n in numbers] |
| Dictionary comprehension | a new dictionary in one line | {n: n ** 2 for n in numbers} |
| Set comprehension | a new set in one line | {n % 2 for n in numbers} |