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:

Items = {}
item = input('Item: ')
while item != '':
  number = int(input('Number sold: '))
  if item in Items:
    Items[item] = Items[item] + number
    
  else:
    Items[item] = number
  item = input('Item: ')

print('Total sales for today:')

for stuff in Items.values():
    print(f'{item} : {stuff}')

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:

for item in Items:
    print(f'{item}: {Items[item]}')

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.

from collections import defaultdict

my_dict = default_dict(lambda: 0)

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:

from collections import defaultdict


def main():
    items = defaultdict(lambda: 0)
    
    while True:
        item = input('Enter an item: ').lower()
        
        if item == '':
            break

        quantity = int(input('Enter the quantity of the item: '))

        items[item] += quantity
        
        print('n')  # make the console output cleaner to look at

    for item in items:
        print(f'{item}: {items[item]}')


if __name__ == '__main__':
    main()
Advertisement