-1

I'm trying to figure out a way to remove the "duplicate" tuples from my list while also accumulating their "values". The tricky part is that they're not necessary true duplicates nor true values so what's the best approach?

Would it be easier to just try and convert my list into a dictionary?

My list of tuples:

lst = [('bday', 1), ('ramen', 2), ('cake', 1), ('ramen', 1), ('cake', 2), ('ramen', 1)]

Expected Output:

 ({'cake': 3, 'birthday': 1, 'ramen': 4})
deedle
  • 105
  • 11

2 Answers2

4

You can use defaultdict:

from collections import defaultdict

mylist = [('birthday', 1), ('ramen', 2), ('cake', 1), ('ramen', 1), ('cake', 2), ('ramen', 1)]

d = defaultdict(int)

for k,v in mylist:
    d[k] += v        

print(d)    
# defaultdict(<type 'int'>, {'cake': 3, 'birthday': 1, 'ramen': 4})
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

There's an algorithm for such an occasion. It's called counting sort! In this case we would have a dictionary with keys being what you want to count, and the amount of occurrences would be the values.

ProfOak
  • 541
  • 4
  • 10