0

I know there's a way to merge lists into a dict by zip function, but once the 'key-list' contains duplicated factors it doesn't works well since many values will be cut. I wonder if there is a good solution to merge lists with the same keys?

assume we have two lists below, one is to be key and another is to be value

    list_k = [1,1,2]
    list_v = [3,6,9]

if I apply zip as usual, we will get following result

    dict = {k:v for k, v in zip(list_k, list_v)}
    #{1:3, 2:9}

however, what I want is as below

    #dict = {1:[3,6],2:[9]}
roy_wang
  • 11
  • 1

1 Answers1

0

You could use collections.defaultdict:

from collections import defaultdict

list_k = [1, 1, 2]
list_v = [3, 6, 9]
merged = defaultdict(list)
for k, v in zip(list_k, list_v):
    merged[k].append(v)
merged = dict(merged)
print(merged)

Output:

{1: [3, 6], 2: [9]}
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40