Skip to content
Advertisement

How do you summarize all the values in a list and print the final items and their final values in an organized manner?

Question: Write a program to help you manage your sales. It should keep asking for an item that has been sold, and how many were sold, until a blank item is entered. It should then print out how many of each item were sold that day.

Code:

JavaScript

This is the code and I’m doing something here that doesn’t print all final values in one go.

The output should look like this:  required output

While mine looks like this: My output

Advertisement

Answer

Error

The error in your code seems to be in your for-loop as I don’t see where the variable item comes from in your f-string. So, I’d recommend you write the for loop as something like:

JavaScript

Recommended Solution

Since you posted a question, I thought I’d also give you a way in which I’d solve this. Use the defaultdict from the collections module and set it to give a default value of 0 to every new key.

JavaScript

This helps so that you can just focus on adding the new quantities without worrying about whether a matching key already exists.

So, the new code would look something like this:

JavaScript
Advertisement