Home > Software engineering >  How to create dictionary that has multiple values from a list?
How to create dictionary that has multiple values from a list?

Time:10-26

I currently have two lists (the real lists are much longer but here's an example:)

month = [12,12,12,12,11,11,11,10,...]
wave_height = [3,6,8,2,4,9,7,9,....]

My goal is to have a dictionary that looks like:

  12: 3, 6, 8, 2
  11: 4, 9, 7
  10: 9, ...

Where key is the month, and values are all the instances of wave_height. How do I do that?

CodePudding user response:

You can use a collections.defaultdict then zip your two lists together to populate the keys and values.

from collections import defaultdict
month = [12,12,12,12,11,11,11,10]
wave_height = [3,6,8,2,4,9,7,9]

data = defaultdict(list)
for m, w in zip(month, wave_height):
    data[m].append(w)

Result

>>> data
defaultdict(<class 'list'>, {12: [3, 6, 8, 2], 11: [4, 9, 7], 10: [9]})

CodePudding user response:

month = [12, 12, 12, 12, 11, 11, 11, 10]
wave_height = [3, 6, 8, 2, 4, 9, 7, 9]

wh = iter(wave_height)
out = {}
for m in month:
    out.setdefault(m, []).append(next(wh))
print(out) # {12: [3, 6, 8, 2], 11: [4, 9, 7], 10: [9]}
  • Related