Reputation: 23
I'm new to Python. I'm trying to zip 2 lists into a dictionary without losing the values of the duplicated keys and keep values as a list in the dictionary.
Example:
list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
I'm trying to get the following outcome:
{'tree': [0.43, -60.5],'cat': [-1.2, 50],'hat': [50]}
Thanks for your help.
Upvotes: 0
Views: 106
Reputation: 8510
just for completeness, this is how I would have do it in my early days programing
>>> list1 = [0.43, -1.2, 50, -60.5, 50]
>>> list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
>>> result=dict()
>>> for k,v in zip(list2,list1):
if k in result:
result[k].append(v)
else:
result[k]=[v]
>>> result
{'hat': [50], 'tree': [0.43, -60.5], 'cat': [-1.2, 50]}
>>>
Upvotes: 0
Reputation: 372
The answer provided by Mike Muller works perfectly well. An alternative, perhaps slightly more pythonic way would be to use defaultdict from the collections library:
from collections import defaultdict
list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = defaultdict(list)
for k, v in zip(list2, list1):
d[k].append(v)
Upvotes: 2
Reputation: 85442
You can use the setdefault method of the dictionary:
list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = {}
for k, v in zip(list2, list1):
d.setdefault(k, []).append(v)
Results:
>>> d
{'cat': [-1.2, 50], 'hat': [50], 'tree': [0.43, -60.5]}
Upvotes: 2