A list finds items by position. A dictionary finds them by a name. If you want the phone number of Ravi, you would like to ask for Ravi, and not for position 7. In this course you make dictionaries of keys and values, add, change and remove pairs, look things up without errors, go through a dictionary with a loop, and count with it. You learn to put a dictionary inside a dictionary, to keep a list as a value, and to group items. A tiny shop with prices, stock and a basket is the project at the end. The practice runs your code on real data and tells you which results are wrong.
5 lessons, about 2 h 30 min5 simulations14 problems10 practice questionsPython in every lesson
A dictionary stores pairs of a key and a value, and finds a value by its key. It is written in curly brackets, with key: value pairs separated by commas. Look up a value with d[key], count the pairs with len, and ask whether a key is there with in, which asks about the keys and not the values. A key must be unique and fixed, such as text, a number or a tuple. A key that is not in the dictionary gives a KeyError.
You change a dictionary by writing to a key: d[key] = value adds a pair if the key is new and replaces the value if it exists. del d[key] and d.pop(key) remove a pair, and pop gives the value back. d.get(key, default) looks up safely and never gives a KeyError. keys, values and items show the whole dictionary, and sum, max and sorted work on them. update adds the pairs of another dictionary.
A for loop over a dictionary goes through the keys, and d.items() gives the key and the value in each round. To count with a dictionary, the key is the thing that you count and the value is how many times you have seen it, and counts[x] = counts.get(x, 0) + 1 does the work, because get gives 0 the first time. The same idea counts letters, words or any items. To find the key with the highest value, go through the items and remember the best so far.
A value of a dictionary can be a list or another dictionary, so a dictionary can hold a record for each key. A lookup with two keys in a row, such as students[name][age], goes down one level at a time. To group items, the value is a list: the first time a key is seen, make an empty list, and then append. A record in a dictionary is easy to read, because each part has a name, such as age and marks. Use get or in at each level to avoid a KeyError.
In this project we write a tiny shop. Two dictionaries hold the prices and the stock, and a list is the shopping basket. The program goes through the basket, refuses items that the shop does not sell, refuses items that are out of stock, takes one item off the shelf for each sale, and adds the price to the total. We plan the rules and the expected answers first, build the program in steps, test the unusual cases, and extend the shop with discounts and a receipt that counts how many of each item were bought.
Log in to join the discussion.
Loading…