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]]}
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]]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With