Search code examples
pythonstringintegernested-lists

Python: Nested list with repeated name of strings and different integers. How can I


If I have the following nested list:

products.store = [['Shampoo', 35], ['Soap', 100], ['Soap', 150],['Towels', 45], ['Shampoo', 55]]

How can I write a program where each product is associated to total amount of products?

So that the output will still be in a nested list, like this: [['Shampoo', 90], ['Soap', 250],['Towels', 45]]

I have tried multiple solutions, but have failed to make the integers associated to a singular product.

Sorry if this is an easy question, it is my first term in university with coding. (Not for homework, a test or something like that). I would just love to learn how to improve my codes and better understand:) Thank you for your help!


Solution

  • Try:

    products = [
        ["Shampoo", 35],
        ["Soap", 100],
        ["Soap", 150],
        ["Towels", 45],
        ["Shampoo", 55],
    ]
    
    out = {}
    for a, b in products:
        out[a] = out.get(a, 0) + b
    
    out = list(map(list, out.items()))
    print(out)
    

    Prints:

    [["Shampoo", 90], ["Soap", 250], ["Towels", 45]]