Python Forum

Full Version: How do I make zip() append a value to a key?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have these two arrays:
arr1 = ['sub1', 'sub1', 'sub2', 'sub1', 'sub1', 'sub2']
arr2 = [1.9   , 2.2   , 9.1   , 7.3   , 4.0   , 5.1   ]
When I do dict(zip(arr1, arr2,)) I get
sub1 : 4, sub2 : 5.1
whereas I was expecting something like
sub1 : (1.9, 2.2, 7.3, 4.0), sub2 : (9.1, 5.1)
(ie the name and then the numbers in a list, tuple or between {}). Does anyone know if zip() can do this or how I can do it another way?

Thanks
When you are setting the key like that it is just overwriting the previous key. You want to first create a list and then append each value to that key's list.

arr1 = ['sub1', 'sub1', 'sub2', 'sub1', 'sub1', 'sub2']
arr2 = [1.9   , 2.2   , 9.1   , 7.3   , 4.0   , 5.1   ]

d = {}
for key, value in zip(arr1, arr2):
    d.setdefault(key,[]).append(value)
        
print(d)
Output:
{'sub1': [1.9, 2.2, 7.3, 4.0], 'sub2': [9.1, 5.1]}