Lists and dictionaries
Keep many values together. A list keeps things in order; a dictionary links each name to a value, like a price list.
In 60 seconds
Lists and dictionaries
Keep many values together. A list keeps things in order; a dictionary links each name to a value, like a price list.
Lists
marks = [78, 92, 65, 88]
print(marks[0]) # first item: 78
print(marks[-1]) # last item: 88
print(len(marks)) # how many items: 4
marks.append(71) # add one to the end
print(marks)
marks[2] = 67 # change the third item
print(marks)| You want to… | Code | Result for [78, 92, 65] |
|---|---|---|
| Get the first item | marks[0] | 78 |
| Get the last item | marks[-1] | 65 |
| Count items | len(marks) | 3 |
| Add an item | marks.append(50) | [78, 92, 65, 50] |
| Check if a value is there | 92 in marks | True |
| Sort | sorted(marks) | [65, 78, 92] |
stations = ["Chennai", "Katpadi", "Bengaluru"]. And you can loop over a list with for, as you did in the last lesson.Dictionaries
prices = {"milk": 30, "bread": 45, "eggs": 7} # made-up prices in rupees
print(prices["bread"]) # look up by key: 45
prices["rice"] = 60 # add a new item
prices["milk"] = 32 # change a price
print(prices)
print("sugar" in prices) # is this key there? False
print(prices.get("sugar", 0)) # get with a default: 0prices["sugar"], stops the program with a KeyError. Check first with in, or use .get(key, default), which gives the default instead of an error.Looping over a dictionary
prices = {"milk": 30, "bread": 45, "eggs": 7}
for item, price in prices.items():
print(f"{item:<6} Rs {price}")Lists and dictionaries together
prices = {"milk": 30, "bread": 45, "eggs": 7}
cart = ["milk", "eggs", "eggs", "bread"]
total = 0
for item in cart:
total += prices[item]
print("Bill: Rs", total)Counting with a dictionary
cart = ["milk", "eggs", "eggs", "bread", "eggs"]
counts = {}
for item in cart:
counts[item] = counts.get(item, 0) + 1
print(counts)- Order matters: balls in an over, stations on a route
- The same value can appear more than once
- You find things by position: first, last, third
- You look things up by a name or code: price of milk, marks of Asha
- Each key appears only once
- You want to count or group things by name
Watch and read more
Lab
A shop bill calculator that adds up a cart from a price board, and counts each item.
The problem
You run a small shop. Finish the two functions:
bill_total(cart, prices):cartis a list of item names (the same item can appear more than once) andpricesis a dictionary of prices. Return the total in rupees. If an item is not on the price board, skip it (add nothing) and print a short message such asNo price for gold, so the shop owner knows.count_items(cart): return a dictionary showing how many of each item are in the cart, for example{"milk": 2, "bread": 1}.
Press Run to test, then Check. Well done for getting this far: this is how real billing software starts!
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Why is it risky to write <code>total += prices[item]</code> without checking first?Reveal
If a customer buys something not on the price board, prices[item] raises a KeyError and the whole bill stops. Checking if item in prices, or using prices.get(item), lets the program handle the missing price calmly and tell the shop owner.
Q2How could you print a proper bill with one line per item, like <code>eggs x2 = Rs 14</code>, using both of your functions?Reveal
First get counts = count_items(cart). Then loop: for item, n in counts.items(): and, if the item has a price, print f"{item} x{n} = Rs {n * prices[item]}". Print bill_total(cart, prices) at the end. Both answers come from the same data, so they should agree.
Questions people ask
Why does counting start at 0?
The index tells Python how many steps to move from the start. The first item is 0 steps away. You get used to it quickly. Negative indexes count from the end: -1 is the last item.
Can a dictionary have two items with the same key?
No. Each key is unique. If you set prices["milk"] again, the old value is replaced. If you need to keep several values for one key, store a list as the value.
What is the difference between sorted(marks) and marks.sort()?
sorted(marks) gives you a new sorted list and leaves the original alone. marks.sort() sorts the original list itself and returns nothing. Both are useful.
Can a list hold different types?
Yes, for example ["Asha", 14, 87.5]. But lists are easiest to use when all items are the same kind. For a record with named parts, a dictionary is clearer: {"name": "Asha", "age": 14}.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.