Explore how to work with lists of dictionaries in Python and apply a filter operation to produce a new list. Learn to add a new key-value pair on the fly and use these skills for tasks such as inventory management.
Key Insights
- The tutorial deals with a list of dictionaries, each dictionary having four key-value pairs: fruit, lbs, price per lb, and in stock (true or false).
- To access the values in the dictionary, one uses square bracket syntax and the name of the object with the key name.
- The aim is to create a new list called medium_priced_fruits by looping through the original list and filtering for fruits that cost more than a dollar per pound but less than two dollars per pound.
- The filter operation also removes any fruits that are not currently in stock.
- A new key-value pair is added to each dictionary called total price, computed by multiplying the pounds of fruit by the price per pound.
- This process illustrates how Python can be used for inventory management tasks, for example, by filtering and manipulating data.
Join us as we tackle this difficult Python programming challenge and learn a few valuable skills along the way!
Starting File
Final File
Video Transcription
Each dictionary in the list has four key-value pairs: fruit, lbs, price per lb, and in stock (true or false). To access them, use square bracket syntax and the name of the object with the key name. For example, to print Apple, you would use: `fruit_list[0]["fruit"]`.
We are going to loop through the list of dictionaries and produce a new list of dictionaries called medium_priced_fruits. This will do a filter operation, and include only those fruits that cost more than a dollar per pound but less than two dollars per pound. It will also filter out those that are not in stock.
We will also add a new key on the fly, called total price, which will be a math calculation of the pounds times the price per pound.
To write this, we don't need to make a function. We will have a medium_price_fruits list and then iterate through the fruit list of dictionaries. Every time, we will ask if the price per pound of the current item is greater than or equal to one, and less than or equal to two. If it is, and the item is in stock (dictionary["in stock"] is true), we will add a new key, called total price, which is the number of pounds times the price per pound. We will then append the dictionary to the medium_price_fruits list.
When done, we will print the medium_price_fruits list to check the output.