Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python merge duplicates in a single list and combine the results

Tags:

python

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

like image 285
Tim Avatar asked Oct 29 '22 22:10

Tim


1 Answers

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()]
like image 128
Karin Avatar answered Nov 15 '22 05:11

Karin