0

I am trying to find the add together the values of a list that are matching a value from another list. My logic is the following:

for all the values in list1, count how many times each values of list1 are in list2, add them together and append them to a dictionary.

my current code is not giving me what I am expected and I am failing to understand why.

  list1 = [1,2,3,4,5]
  list2= [1,1,1,2,2,2,3,3,4,4,5]

  count = dict()
  for i in list1:
     if i in list2:

     count[i] = sum(i in list1 for i in list2)

  else:
     count[i] = 1


 print(count)

As a result I get this: {1: 11, 2: 11, 3: 11, 4: 11, 5: 11}

and I am trying to find: {1:3, 2:3, 3:2, 4:2, 5:1}

Thank you for any help!

Murcielago
  • 905
  • 1
  • 8
  • 30

1 Answers1

0

I guess this is what you want

list1 = [1,2,3,4,5]
list2= [1,1,1,2,2,2,3,3,4,4,5]

count = {i:0 for i in list1}
for i in list2:
    if i in list1:
        count[i] += 1

print(count)
Chao Peng
  • 179
  • 8
  • Thank you so much Chao Peng, I spent so many hours and could not figure it out. I appreciate it. – Murcielago Oct 16 '19 at 03:38
  • You @LeLionJaune are welcome! I'm new to this community, could you let me know how to get my answer accepted? – Chao Peng Oct 16 '19 at 10:51
  • i think that the answers get upvoted by others depending on good, thoughtful and relevant they are. not sure if it gets formaly accepted. thank you again for your help! – Murcielago Oct 16 '19 at 18:03