Reputation: 21
I have two lists that I would like to associate by index as key value pairs in a dictionary. The key list has multiple identical elements. I would like the all elements in the value list to be paired as a list of list. I am using the list.append() method, but this is not giving me the desired output. Any recommendations on the code or should I be looking at the problem in a different way?
list1 = ['a', 'b', 'b', 'b', 'c']
list2 = [['1', '2', '3'], ['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12'], ['13', '14', '15']]
combo = {}
for i in range(len(list1)):
if list1[i] in combo:
combo[list1[i]].append(list2[i])
else:
combo[list1[i]] = list2[i]
Current output:
{'a': ['1', '2', '3'], 'b': ['4', '5', '6', [ '7', '8', '9'], ['10', '11', '12']], 'c': ['13', '14', 15']}
Desired output:
{'a': [['1', '2', '3']], 'b': [['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12']], 'c': [['13', '14', 15']]}
Upvotes: 1
Views: 6593
Reputation: 69735
If you want a more Pythonic response, you can also use a dict
comprension:
output = {key: [value] for key, value in zip(list1, list2)}
Upvotes: 1
Reputation: 896
Try out this code. It's working when I tried with the same input that you have given.
#Input
list1= ['a','b', 'b','b', 'c']
list2 = [['1', '2', '3'], ['4', '5', '6'], [ '7', '8', '9'], ['10','11','12'], ['13', '14', '15']]
combo= {}
for index, value in enumerate(list1):
if value in combo.keys():
combo[value].append(list2[i])
else:
combo[value]= []
combo.append(list2[i])
#output
print(combo)
{'a': [['1', '2', '3']],'b': [['4', '5', '6'], ['7', '8', '9'], ['10', '11', '12']], 'c': [['13', '14', '15']]}
Upvotes: 0
Reputation: 29071
Use a defaultdict
, with the empty list an starting value
result = defaultdict(list)
for key, value in zip(list1, list2):
result[key].append(value)
Upvotes: 4