ive got a list in python that looks like
['Nickey, 20', 'John, 50', 'Nickey, 30']
i simply want it to remove the duplicates however, combine the numbers so the result is
['Nickey, 50', 'John, 50']
i've tried the following
A = {'a':1, 'b':2, 'c':3}
B = {'b':3, 'c':4, 'd':5}
c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
print c
but as you can see the list is differently formatted, i pulled mine from a txt file...
Is there a way to use get, set, union but with my formatting of a list - and can i do it with one list instead of merging 2
One approach is to create a dictionary to store the total count per name:
from collections import defaultdict
people = ['Nickey, 20', 'John, 50', 'Nickey, 30']
people_map = defaultdict(int)
for person in people:
name, number_str = person.split(', ')
people_map[name] += int(number_str)
print ['{}, {}'.format(person, total) for person, total in people_map.iteritems()]
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