Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine items in list

Python3:

dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}

I have the above dictionary with the values being a list within a list. What I would like to do is combine the items within the list that are the same and add the integer to that value.

eg. since Toyota is in there 3x then combine all the numbers together to give me another list

[Toyota, 51]

Final result should be does not need to be in this order

dct = {'Mazda': [['Ford', 95], ['Toyota', 51], ['Chrysler', 52]]}
like image 544
Josh Benoza Avatar asked Dec 02 '25 15:12

Josh Benoza


1 Answers

For the input in the question:

dct = {'Mazda': [['Ford', 95],  ['Toyota', 20], ['Chrysler', 52],
                 ['Toyota', 5], ['Toyota', 26]]}

Try this:

from collections import defaultdict

for k, v in dct.items():
    aux = defaultdict(int)
    for car, num in v:
        aux[car] += num
    dct[k] = map(list, aux.items())

Now dct contains the expected result:

dct
=> {'Mazda': [['Ford', 95], ['Toyota', 51], ['Chrysler', 52]]}
like image 110
Óscar López Avatar answered Dec 04 '25 07:12

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!