Reputation: 152
There are 2 lists. What I am trying to do is to find the occurrence of first list elements and will hold the values of second list for a key in first list and in the end, it will become dictionary holding specific keys from list 1 and values from list 2
Input:
list1 = ['A', 'A', 'B', 'B', 'C', 'D']
list2 = [1, 2, 3, 4, 5, 6]
Expected Output:
{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D':[6]}
Current Output:
{'A': [1, 2], 'B': [4], 'C': []}
What I tried so far,
values = [list2[0]]
key = list1[0]
dic = {}
for i in range(1, len(list1)):
if list1[i] == list1[i - 1]:
values.append(list2[i])
elif list1[i] != list1[i - 1]:
dic.update({key: values})
values = []
key = list1[i]
print(dic)
List 1 and List 2 are always equal in length and sorted
Upvotes: 2
Views: 54
Reputation: 27385
You can also use defaultdict
from collections
from collections import defaultdict
list1 = ['A', 'A', 'B', 'B', 'C', 'D']
list2 = [1, 2, 3, 4, 5, 6]
d = defaultdict(list)
for key, value in zip(list1, list2):
d[key].append(value)
print(dict(d))
{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D': [6]}
Upvotes: 1
Reputation: 106553
You can use dict.setdefault
to initialize each distinct key with a new list to append values to:
output = {}
for key, value in zip(list1, list2):
output.setdefault(key, []).append(value)
output
would become:
{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D': [6]}
Demo: https://replit.com/@blhsing/InstructiveNoxiousCollaborativesoftware
Upvotes: 1
Reputation: 306
There are multiple small issues with your code:
values
with an empty list, you loose the first valueThese issues could be fixed the following way:
dic.update({key: values})
below the loopvalues = []
to values = [list2[i]]
Upvotes: 1