2

I am trying to build a function to merge two lists into a dictionary, but the "key" list contains duplicates. I would like to sum the values based on the key. The lists could have any number of values (but each list would have the same number).

I have tried out many different codes that I have found through Googling, but none of them were for this situation, and none worked quite right. I'm just getting started with learning Python, so I'm sure there's something I'm missing!

my_dict={}
def merge_lists(my_dict):
    newlist={k: sum(i[k] for i in my_dict) for k in my_dict[0]}
    return newlist       

If I start with these lists: key_list=[1, 5, 3, 8, 5, 8, 3], value_list=[2, 3, 7, 1, 4, 9, 2]

I'm looking for this result: {'1':2, '3':9, '5':7, '8':10}

aritten
  • 29
  • 2
  • @DanielMesejo in this case, the duplicate keys are in the same dictionary, so I think they need something like a defaultdict with a loop. Maybe you can find that duplicate. – cs95 Jan 16 '19 at 21:24
  • 1
    @coldspeed: https://stackoverflow.com/questions/31430384/how-to-sum-values-of-tuples-that-have-same-name-in-python – Dani Mesejo Jan 16 '19 at 21:29
  • 1
    ufff, accepted answer there is horrible. – wim Jan 16 '19 at 21:32
  • 1
    @wim true. But the other answer has more upvotes now. Do you think it could have been closed differently? it's a duplicate all right. Maybe another Q&A answers better? – Jean-François Fabre Jan 16 '19 at 21:41
  • I have already tried the solutions posted in both of those (and any other post that was even remotely similar), and neither worked. – aritten Jan 16 '19 at 21:45
  • Yeah, I mean I guess none of them would really work because you need the zip. – wim Jan 16 '19 at 21:53

1 Answers1

2

A plain old loop is best here:

>>> data = {}
>>> for key, val in zip(key_list, value_list): 
...     data[key] = data.get(key, 0) + val 
... 
>>> data 
{1: 2, 5: 7, 3: 9, 8: 10}
wim
  • 338,267
  • 99
  • 616
  • 750