Python Forum
How do I make zip() append a value to a key?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I make zip() append a value to a key?
#1
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
Reply
#2
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]}
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,525 Apr-22-2020, 01:01 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020