Reputation: 27
So I have a list of tuples that looks something like:
visits_country = (['123', 'United States'], ['456', 'United States'], ['1', 'Canada'], ['24', 'Canada'], ['12', 'Mexico'])
I've managed to sum all of the first entries which have a second entry 'United States' as follows
us_visits = [x[0] for x in visits_country if x[1] == 'United States']
total_us_visits = sum(map(int, us_visits))
Is there a way to automate this task so that I don't have to write a whole new line for every single country to sum all of its paired integers? Possibly a function that will return a list with each unique country and its total visits from each occurrence in the original list (visits_country)?
Thanks!
Upvotes: 0
Views: 41
Reputation: 2817
Easy:
visits_country = (['123', 'United States'], ['456', 'United States'],
['1', 'Canada'], ['24', 'Canada'], ['12', 'Mexico'])
dictionary = {}
for count, country in visits_country:
dictionary[country] = dictionary.get(country, 0) + int(count)
print dictionary
Upvotes: 3
Reputation: 155506
Yup. The most obvious approaches are to use either collections.Counter
or itertools.groupby
, the latter requiring a presort. For example:
from itertools import groupby
from operator import itemgetter
visits_country.sort(itemgetter(1))
sums = [(sum(int(x) for _, x in grp), key)
for key, grp in groupby(visits_country, itemgetter(1))]
or:
from collections import Counter
counts = Counter()
for visits, country in visits_country:
counts[country] += int(visits)
Upvotes: 0