- Lab
-
Libraries: If you want this lab, consider one of these libraries.
Create Basic Lists and Dictionaries for Data Analysis in Python
Raw inventory data is only useful once it's organized so you can review it and keep it current. In this lab, you'll use Python's core collections (lists, sets, and dictionaries) to look up products, update them, compare product categories across two stores, and track stock levels. You'll finish by summarizing the inventory with Python's built-in functions, a foundation you'll reuse in every data analysis task that follows.
Lab Info
Table of Contents
-
Challenge
Step 1: Retrieve products from the inventory list
Every data analysis starts with getting the data into a shape you can work with, and Python's built-in collections are the quickest way to do that. In this lab, you'll organize a neighborhood store's inventory in a Jupyter notebook. You'll keep its products in a list you can look up and change, compare its product categories with a second store's using sets, track how many of each product are on hand in a dictionary, and finish with a short inventory report built from Python's built-in functions.
To begin, you'll work with the store's product list. A list is an ordered collection, so every product has a position, called an index. Indexes count up from
0at the front of the list and down from-1at the end. By the end of this step, you'll be able to pull out any single product by its position and any run of products with a slice. The notebookstore_inventory.ipynbis already in the workspace with most of its code written. Openstore_inventory.ipynbby double-clicking on the file name.A notebook is made of cells, and the kernel is the Python process that runs them. Run all of the code cells in this step by selecting each one in turn and pressing
Shift+Enter.info> Feeling stuck? Open
store_inventory_solution.ipynbfrom the File > Open menu to see every cell completed. Give each blank a try on your own first. The solution notebook is your safety net, not your starting point.Replace every
____in a cell before you run it. If you run a cell with a placeholder still in it, Python stops withNameError: name '____' is not defined, which means the blank still needs your code. The first cell creates theproductslist with eight product names, in the order they appear on the store's shelf list. There's nothing to type in this cell. Run it as is.products = ["Notebook", "Pencil", "Stapler", "Desk Lamp", "Backpack", "Water Bottle", "Calculator", "Highlighter"] productsExpected output
You'll see all eight products, from
'Notebook'to'Highlighter'.Retrieve a product by its position
To get one item from a list, put its index in square brackets after the list's name. Index
0is the first product.Replace
____with the index0, typed as a number without quotes.products[____]Expected output
You'll see
'Notebook'.Index
3is the fourth product, because indexes count from zero.Replace
____with the index3.products[____]Expected output
You'll see
'Desk Lamp'.Retrieve a product from the end of the list
A negative index counts backward from the end of the list. Index
-1is always the last item, no matter how long the list is. Replace____with the index-1.products[____]Expected output
You'll see
'Highlighter'.Index
-2is the second-to-last item. Replace____with the index-2.products[____]Expected output
You'll see
'Calculator'.Read a position that doesn't exist
The list has eight items, so its last valid index is
7. The next cell asks for index8, which doesn't exist. This error is expected: Python raises anIndexErrorwhenever you ask a list for a position it doesn't have. There's nothing to type in this cell. Run it as is.products[8]Expected output
You'll see
IndexError: list index out of range.The error stops only this cell, so continue with the next one.
Retrieve a range of products with a slice
To get a range of items, use a slice. A slice has the form
start:endinside the square brackets, and it returns a new list that starts at thestartindex and stops just before theendindex.Replace
____with the slice1:4.products[____]Expected output
You'll see
['Pencil', 'Stapler', 'Desk Lamp'], the products at indexes1,2, and3.Leave out the start index and the slice begins at the front of the list.
Replace
____with the slice:3.products[____]Expected output
You'll see
['Notebook', 'Pencil', 'Stapler'].Leave out the end index and the slice runs to the end of the list. Combined with a negative start index, this gets the last few items.
Replace
____with the slice-3:.products[____]Expected output
You'll see
['Water Bottle', 'Calculator', 'Highlighter'].You can now retrieve one product by index and a group with a slice. Next, you'll change the list by adding and removing products.
-
Challenge
Step 2: Update the inventory list
With indexing and slicing, you can look up any product in the list. The store's inventory changes every week, though, so here you'll change the list itself as products arrive and are discontinued. Each cell ends with prewritten code that displays the list after your change so you can watch it update. By the end of this step, you'll know how to add a product to the end of a list, insert one at a specific position, and remove one by name or by position. Run all of the code cells in this step by selecting each one in turn and pressing
Shift+Enter, after you replace the____the cell contains.warning> These cells change the list in place, which means they edit the list itself instead of making a copy. If you run one of them a second time after filling in its blank, the list changes again and the results no longer match these instructions. If that happens, select Kernel > Restart Kernel, then run the cells again from the top of the notebook down to where you left off.
Add a product to the end of the list
A new product, sticky notes, has arrived. The
append()method adds one item to the end of a list. You call a method by typing the list's name, a dot, and the method name followed by parentheses that hold the value, such asproducts.append(item).Replace
____with a call toappend()onproductsthat passes the string"Sticky Notes".____ productsExpected output
You'll see nine products, with
'Sticky Notes'at the end.Insert a product at a specific position
Printer paper is the store's best seller, so it belongs at the front of the list. The
insert()method takes an index and an item, places the item at that index, and shifts every later item one position to the right.Replace
____with a call toinsert()onproductsthat passes the index0and the string"Printer Paper".____ productsExpected output
You'll see
'Printer Paper'first, followed by'Notebook'and the rest of the products.Remove a product by name
The store has discontinued its stapler. The
remove()method deletes the first item that matches the value you pass it.Replace
____with a call toremove()onproductsthat passes the string"Stapler".____ productsExpected output
You'll see the list without
'Stapler'.Remove a product by position
The order for sticky notes, the last product in the list, was canceled. The
pop()method removes an item by position and returns it, so you can store the removed item in a variable. When you callpop()with no index, it removes the last item.Replace
____with a call topop()onproductswith nothing between the parentheses.canceled = ____ print(canceled) print(products)Expected output
You'll see
Sticky Noteson the first line, followed by the eight remaining products from'Printer Paper'to'Highlighter'.info> If the first line shows
Printer Paperinstead, you passed an index topop(). Select Kernel > Restart Kernel, remove the index so that nothing is between the parentheses ofpop(), and run the cells again from the top.You can now add, insert, and remove list items. Next, you'll turn the product categories into sets and compare them across two stores.
-
Challenge
Step 3: Compare categories across stores
The product list is now current, and each product belongs to a category. Here, you'll turn category data into sets and compare the first store's categories with those of a second store run by the same owner. A set is an unordered collection that holds each value only once, which makes it the right tool for questions such as "which categories do both stores carry?" By the end of this step, you'll be able to build a set from a list and combine two sets to find what they share, what is unique to each, and everything they cover together. In
store_inventory.ipynb, scroll down to the Step 3: Compare categories across stores heading. Run all of the code cells in this step by selecting each one in turn and pressingShift+Enter, after you replace any____the cell contains.The first cell creates
product_categories, a list with one category for each product inproducts, in the same order. Several products share a category. There's nothing to type in this cell. Run it as is.product_categories = ["Office Supplies", "Stationery", "Stationery", "Electronics", "Bags", "Kitchen", "Electronics", "Stationery"] product_categoriesExpected output
You'll see eight categories, with
'Stationery'appearing three times and'Electronics'appearing twice.Remove duplicates with a set
Passing a list to
set()builds a set from it, which keeps each value exactly once.Replace
____with a call toset()that passesproduct_categories.store_a_categories = ____ store_a_categoriesExpected output
You'll see five categories:
'Bags','Electronics','Kitchen','Office Supplies', and'Stationery'.info> Sets have no order of their own. Jupyter displays a set's values sorted to make them easier to read, but you can't retrieve a set's values by index the way you can with a list.
Create the second store's categories
You can also write a set directly by putting its values in curly braces. The second store carries some of the same categories as the first store and some different ones. There's nothing to type in this cell. Run it as is.
store_b_categories = {"Electronics", "Bags", "Toys", "Stationery", "Garden"} store_b_categoriesExpected output
You'll see
{'Bags', 'Electronics', 'Garden', 'Stationery', 'Toys'}.Find the categories both stores carry
The
intersection()method returns a new set of the values that appear in both sets. Here, those are the categories both stores carry.Replace
____with a call tointersection()onstore_a_categoriesthat passesstore_b_categories.shared_categories = ____ shared_categoriesExpected output
You'll see
{'Bags', 'Electronics', 'Stationery'}.Find the categories only one store carries
The
difference()method returns the values in the first set that are not in the set you pass it. Starting from the first store shows the categories only it carries.Replace
____with a call todifference()onstore_a_categoriesthat passesstore_b_categories.____Expected output
You'll see
{'Kitchen', 'Office Supplies'}.Starting from the second store gives a different answer, because
difference()depends on which set you call it on.Replace
____with a call todifference()onstore_b_categoriesthat passesstore_a_categories.____Expected output
You'll see
{'Garden', 'Toys'}.Combine both stores' categories
The
union()method returns every value that appears in either set, each one exactly once.Replace
____with a call tounion()onstore_a_categoriesthat passesstore_b_categories.all_categories = ____ all_categoriesExpected output
You'll see seven categories, from
'Bags'to'Toys'.You can now remove duplicates with a set and compare two sets. Next, you'll track stock levels in a dictionary.
-
Challenge
Step 4: Track stock levels with a dictionary
The product list tells you what the store sells, but not how much of each product is on hand. Here, you'll complete a dictionary named
stockin which each key is a product name and each value is the quantity on hand, so each product maps directly to its stock level. You'll then look up quantities and update the dictionary as products sell, arrive, and are discontinued. By the end of this step, you'll be able to create a dictionary, read a value by its key, change a value, add a new key, and remove a key.warning> Like the cells in Step 2, these cells change their data in place. If you run one of them twice after filling in its blank, select Kernel > Restart Kernel, then run the cells again from the top of the notebook. A dictionary is written in curly braces as
key: valuepairs separated by commas. The first cell createsstockwith one entry for each of the eight products currently inproducts. Every entry is written except the value for"Pencil".Replace
____with the number120, typed without quotes so it's a number rather than text.stock = { "Printer Paper": 40, "Notebook": 25, "Pencil": ____, "Desk Lamp": 6, "Backpack": 12, "Water Bottle": 30, "Calculator": 9, "Highlighter": 55, } stockExpected output
You'll see all eight products with their quantities, from
'Printer Paper': 40to'Highlighter': 55.info> If the output shows
'Pencil': '120'with quotes around the number, you typed120as text, which makessum()andmin()fail in Step 5. Remove the quotes and run the cell again.Look up a stock level
To read a value, put its key in square brackets after the dictionary's name.
Replace
____with the key"Pencil", typed in quotes because the key is a string.stock[____]Expected output
You'll see
120.info> If you see
NameError: name 'Pencil' is not defined, you left out the quotes. Type"Pencil"with them and run the cell again.Look up a product that might be missing
The stapler was removed from the product list earlier in the lab, so it has no entry in
stock. Reading a missing key with square brackets raises an error, but theget()method returns a default value that you pass as its second argument instead.Replace
____with a call toget()onstockthat passes the key"Stapler"and the default0.____Expected output
You'll see
0.Record a sale
Five notebooks just sold. The
-=operator subtracts from the current value and stores the result under the same key.Replace
____with a statement that subtracts5from the"Notebook"entry using-=.____ stock["Notebook"]Expected output
You'll see
20, down from25.info> If you see
5, you typed=instead of-=. If you see25, you left out the=. Either way, select Kernel > Restart Kernel, fix the statement, and run the cells again from the top.Record a delivery
Twenty desk lamps just arrived. The
+=operator adds to the current value.Replace
____with a statement that adds20to the"Desk Lamp"entry using+=.____ stock["Desk Lamp"]Expected output
You'll see
26, up from6.info> If you see
20, you typed=instead of+=. If you see6, you left out the=. Either way, select Kernel > Restart Kernel, fix the statement, and run the cells again from the top.Add a new product
The store has started carrying scissors. Assigning a value to a key that isn't in the dictionary yet creates a new entry. Dictionaries keep keys in the order you add them, so the new entry appears at the end.
Replace
____with a statement that assigns15to a new"Scissors"key.____ stockExpected output
You'll see nine entries, ending with
'Scissors': 15.Remove a discontinued product
The store has discontinued its calculator. The
delstatement removes a key and its value from the dictionary. You writedel, a space, and then the entry the same way you read it, with the key in square brackets.Replace
____with adelstatement for the"Calculator"key.____ stockExpected output
You'll see eight entries, without
'Calculator'.You now know how to read, change, add, and remove dictionary entries. Next, you'll use Python's built-in functions to summarize the inventory.
-
Challenge
Step 5: Summarize the inventory
The store's data now lives in three collections: the
productslist, theall_categoriesset, and thestockdictionary. Here, you'll pass those collections to Python's built-in functions to answer summary questions about the inventory, storing each answer in a variable, then combine the answers into a short report. By the end of this step, you'll be able to count, total, compare, and sort the items in any collection with a single function call.The store's data now lives in three collections: the
productslist, theall_categoriesset, and thestockdictionary. In this step, you'll use Python's built-in functions to answer summary questions about the inventory, store each answer in a variable, and combine the answers into a short report. Built-in functions are ready to use without importing anything. By the end of this step, you'll be able to count, total, compare, and sort inventory data using built-in functions. Instore_inventory.ipynb, scroll down to the Step 5: Summarize the inventory heading.Run all of the code cells in this step by selecting each one in turn and pressing
Shift+Enter, after you replace any____the cell contains.info> These cells use variables from Steps 2 to 4. If you restarted the kernel, run the cells from the top of the notebook first.
Count items
The
len()function returns the number of items in any collection. Start with the product list. It's separate fromstock, so the Step 4 changes tostockdidn't change it.Replace
____with a call tolen()that passesproducts.product_count = ____ product_countExpected output
You'll see
8.The same function counts the distinct categories across both stores.
Replace
____with a call tolen()that passesall_categories.category_count = ____ category_countExpected output
You'll see
7.Total the stock on hand
The
values()method gives you just a dictionary's values, here the quantities. Thesum()function adds them up to give the total units in stock.Replace
____with a call tosum()that passesstock.values().total_units = ____ total_unitsExpected output
You'll see
318.Find the lowest and highest stock levels
The
min()function returns the smallest value in a collection, which here is the lowest stock level.Replace
____with a call tomin()that passesstock.values().lowest_stock = ____ lowest_stockExpected output
You'll see
12.The
max()function returns the largest value, which here is the highest stock level.Replace
____with a call tomax()that passesstock.values().highest_stock = ____ highest_stockExpected output
You'll see
120.info> If a cell in this section shows a
TypeErroror a product name instead of a number, you passedstockinstead ofstock.values(). Add.values()and run the cell again.Sort the data for review
The
sorted()function returns a new list with the items in order, alphabetically for strings. It leaves the original list unchanged, soproductskeeps its current order.Replace
____with a call tosorted()that passesproducts.____Expected output
You'll see the eight products in alphabetical order, from
'Backpack'to'Water Bottle'.When you pass a dictionary to a built-in function such as
sorted(), the function works on the dictionary's keys.Replace
____with a call tosorted()that passesstock.____Expected output
You'll see the eight product names in
stockin alphabetical order, including'Scissors'.Print the inventory report
The last cell brings everything together. It prints a short inventory report from the variables you filled in during this step. The code uses f-strings, which insert a variable's value wherever its name appears in curly braces (
{}). There's nothing to type in this cell. Run it as is.print("Inventory report") print(f"Products tracked: {product_count}") print(f"Categories across both stores: {category_count}") print(f"Total units in stock: {total_units}") print(f"Lowest stock level: {lowest_stock}") print(f"Highest stock level: {highest_stock}")Well done. You organized a store's inventory from start to finish in a Jupyter notebook and turned it into a printed inventory report.Expected output
You'll see the report:
Inventory report Products tracked: 8 Categories across both stores: 7 Total units in stock: 318 Lowest stock level: 12 Highest stock level: 120You looked up products by index and by slice, then kept the product list current by appending, inserting, and removing items. You compared two stores' categories with set intersection, difference, and union, and you tracked stock levels in a dictionary that you read, updated, extended, and pruned.
The report you just printed came from
len(),sum(),min(), andmax(). The same collections and built-in functions are the starting point for most data analysis you'll do in Python.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.