Python from zeroBeginnerLesson 1037 min read

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.

Lesson in motion

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.

1/4
In simple words
A list is like a shopping list on paper: items written one below the other, in order. A dictionary is like the price board at a kirana shop: each item has its price next to it. You look up "milk" and find its price.

Lists

A list is written with square brackets, with commas between the items. Each item has a position number called an index, and counting starts at 0.
Python: a list of markspython
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…CodeResult for [78, 92, 65]
Get the first itemmarks[0]78
Get the last itemmarks[-1]65
Count itemslen(marks)3
Add an itemmarks.append(50)[78, 92, 65, 50]
Check if a value is there92 in marksTrue
Sortsorted(marks)[65, 78, 92]
Lists can hold text too: stations = ["Chennai", "Katpadi", "Bengaluru"]. And you can loop over a list with for, as you did in the last lesson.

Dictionaries

A dictionary stores key: value pairs inside curly brackets. You look things up by key, not by position.
Python: a price boardpython
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: 0
Watch out
Asking for a key that is not there, like prices["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

Python: print the price boardpython
prices = {"milk": 30, "bread": 45, "eggs": 7}
for item, price in prices.items():
    print(f"{item:<6} Rs {price}")

Lists and dictionaries together

Real programs often use both. The shopping list says what you bought (a list, and an item can appear twice). The price board says how much each thing costs (a dictionary).
Python: a first billpython
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

A dictionary is also great for counting. Start empty. For each item, add 1 to its count.
Python: how many of each?python
cart = ["milk", "eggs", "eggs", "bread", "eggs"]
counts = {}
for item in cart:
    counts[item] = counts.get(item, 0) + 1
print(counts)
Use a list when…
  • 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
Use a dictionary when…
  • 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
Try this. Add "rice" to the price board with a price of your choice, and add rice to the cart. Run the bill again. Did the total go up by the right amount?

Watch and read more

Lab

A shop bill calculator that adds up a cart from a price board, and counts each item.

~15 min

The problem

You run a small shop. Finish the two functions:

  1. bill_total(cart, prices): cart is a list of item names (the same item can appear more than once) and prices is 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 as No price for gold, so the shop owner knows.
  2. 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.

Output

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.

Please sign in to continue.

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.

Sign in to take the test and save your progress