How to accumulate total in tuple?
Question:
I have a tuple like this:
fruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')]
And I try to return total for each label. So 16 + 360 + 6… for Watermeloenen
So I try it like this:
import locale
from locale import atof, setlocale, LC_NUMERIC
import itertools
import operator
def accumulate_first(l):
locale._override_localeconv["thousands_sep"] = "."
locale._override_localeconv["decimal_point"] = ","
locale.setlocale(locale.LC_ALL, locale='de_DE.UTF-8')
it = itertools.groupby(l, operator.itemgetter(0))
for key, subiter in it:
yield key, sum(locale.atof(key[0]) for key in subiter)
But then the return value is:
[('16', 16.0), ('360', 360.0), ('6', 6.0), ('75', 75.0), ('9', 9.0), ('688', 688.0), ('22', 22.0)]
Question: how can I improve this?
Answers:
Build a dictionary keyed on fruit name. You can then directly look up the total "count"
fruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')]
fruit_dict = {}
for n, f in fruit_list_amount:
fruit_dict[f] = fruit_dict.get(f, 0) + int(n)
print(fruit_dict)
Output:
{'Watermeloenen': 466, 'Appels': 688, 'Sinaasappels': 22}
I have a tuple like this:
fruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')]
And I try to return total for each label. So 16 + 360 + 6… for Watermeloenen
So I try it like this:
import locale
from locale import atof, setlocale, LC_NUMERIC
import itertools
import operator
def accumulate_first(l):
locale._override_localeconv["thousands_sep"] = "."
locale._override_localeconv["decimal_point"] = ","
locale.setlocale(locale.LC_ALL, locale='de_DE.UTF-8')
it = itertools.groupby(l, operator.itemgetter(0))
for key, subiter in it:
yield key, sum(locale.atof(key[0]) for key in subiter)
But then the return value is:
[('16', 16.0), ('360', 360.0), ('6', 6.0), ('75', 75.0), ('9', 9.0), ('688', 688.0), ('22', 22.0)]
Question: how can I improve this?
Build a dictionary keyed on fruit name. You can then directly look up the total "count"
fruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')]
fruit_dict = {}
for n, f in fruit_list_amount:
fruit_dict[f] = fruit_dict.get(f, 0) + int(n)
print(fruit_dict)
Output:
{'Watermeloenen': 466, 'Appels': 688, 'Sinaasappels': 22}