Show contents
Chapter 4 of 7 · 20 min
Filter, count, sort
By the end of this chapter, you'll be able to
- Filter the rows of a dataset with a condition
- Count rows by category with a dictionary
- Add up a value by category
- Sort results and find the largest value
Filtering: keeping the rows you care about
Filtering means keeping only the rows that meet a condition. You go through the rows with a loop, and add the ones that pass the test to a new list, with append.
sales = [
{"brand": "Tecno", "price": 85_000},
{"brand": "Samsung", "price": 145_000},
{"brand": "Itel", "price": 45_000},
{"brand": "Tecno", "price": 120_000},
{"brand": "Samsung", "price": 95_000},
{"brand": "Tecno", "price": 70_000},
]
big = []
for sale in sales:
if sale["price"] > 100_000:
big.append(sale)
print(len(big), "sales over 100,000 CFA francs")
for sale in big:
print(sale["brand"], sale["price"])
2 sales over 100,000 CFA francs
Samsung 145000
Tecno 120000
Here the data is already made of numbers: in a real CSV, remember to convert with int() when reading each row. The _ separator in 100_000 only makes the number easier to read: Python ignores it.
Counting by category
To know how many phones of each brand were sold, you use a dictionary as a set of counters: the key is the brand, the value is the number of sales. counters.get(brand, 0) reads this brand's counter, or 0 if we have not seen it yet.
sales = [
{"brand": "Tecno", "price": 85_000}, {"brand": "Samsung", "price": 145_000},
{"brand": "Itel", "price": 45_000}, {"brand": "Tecno", "price": 120_000},
{"brand": "Samsung", "price": 95_000}, {"brand": "Tecno", "price": 70_000},
]
counters = {}
revenue = {}
for sale in sales:
brand = sale["brand"]
counters[brand] = counters.get(brand, 0) + 1
revenue[brand] = revenue.get(brand, 0) + sale["price"]
print(counters)
print(revenue)
{'Tecno': 3, 'Samsung': 2, 'Itel': 1}
{'Tecno': 275000, 'Samsung': 240000, 'Itel': 45000}
The same move is used to count (add 1) and to add up (add the price). A brand's revenue is the sum of its sales.
Each brand has its number of sales.
Text description of the animation
- Three sales: two Tecno and one Itel.
- The dictionary of counters is empty.
- Tecno has no counter yet: get returns 0, we store 0 + 1.
- Itel is new: its counter starts at 1.
- Tecno already exists: 1 + 1 = 2.
- Each brand has its number of sales.
Sorting and finding the maximum
sorted(list) puts a list of numbers in ascending order; with reverse=True, in descending order. To find which sale is the biggest, not just its amount, you keep the best row seen so far:
sales = [
{"brand": "Tecno", "price": 85_000}, {"brand": "Samsung", "price": 145_000},
{"brand": "Itel", "price": 45_000}, {"brand": "Tecno", "price": 120_000},
]
prices = []
for sale in sales:
prices.append(sale["price"])
print("most to least expensive:", sorted(prices, reverse=True))
best = sales[0]
for sale in sales:
if sale["price"] > best["price"]:
best = sale
print("biggest sale:", best["brand"], best["price"])
most to least expensive: [145000, 120000, 85000, 45000]
biggest sale: Samsung 145000
Mini-lab: sales by brandPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: Tecno sales
With the chapter's sales list, print the number of Tecno phones sold for less than 100,000 CFA francs, then the lowest price among all Samsung sales.
Hint 1
if sale["brand"] == "Tecno" and sale["price"] < 100_000.Hint 2
min() on that list.Show the solution and common mistakes
sales = [
{"brand": "Tecno", "price": 85_000}, {"brand": "Samsung", "price": 145_000},
{"brand": "Itel", "price": 45_000}, {"brand": "Tecno", "price": 120_000},
{"brand": "Samsung", "price": 95_000}, {"brand": "Tecno", "price": 70_000},
]
affordable_tecno = 0
samsung_prices = []
for sale in sales:
if sale["brand"] == "Tecno" and sale["price"] < 100_000:
affordable_tecno = affordable_tecno + 1
if sale["brand"] == "Samsung":
samsung_prices.append(sale["price"])
print(affordable_tecno, "Tecno under 100,000 CFA francs")
print("Cheapest Samsung:", min(samsung_prices))
2 Tecno under 100,000 CFA francs
Cheapest Samsung: 95000
Common mistakes:
- Using
orinstead ofand: you would count every Tecno sale and every sale under 100,000 CFA francs, Itel included. - Calling
min()on an empty list (if there were no Samsung sales): Python raisesValueError. Check withif samsung_prices:first.
Summary
- 1Filtering means going through the rows and keeping, in a new list, the ones that meet a condition.
- 2A dictionary of counters, with get(key, 0) + 1, counts the rows of each category.
- 3The same move, adding a value instead of 1, gives a total per category.
- 4sorted puts a list in order; to know which row is the largest, keep the best row seen so far.
- 5Clean categories (strip, capitalize) before counting.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.