Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New to Python and trying to find out how to gather the quantity of one specific item in a nested list

I’m trying to figure out a code that will go
through all items of the list, and keep a count of how many
times the given item occurs, without the count funtion!

This is my code:

    shopping_cart= [
        ['Soap', 'Floss', 'Hand Sanitizer','Baby wipes'],
        ['Chickpeas', 'Blueberries', 'Granola'],
        ['Crayons','Construction paper','Printer ink']
        ]

    count = 0
    for [i] in shopping_cart:
        count+=len(shopping_cart)
        print (count)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think the easiest way to do this sort of task is to just make a dictionary, add every item to it and then you can get the count for every item.

shopping_cart = [
   ['Soap', 'Floss', 'Hand Sanitizer','Baby wipes'],
   ['Chickpeas', 'Blueberries', 'Granola'],
   ['Crayons','Construction paper','Printer ink']
]


items = {}

for row in shopping_cart:
   for item in row:
       if item not in items:
           items[item] = 0
       items[item] += 1

print(items)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading