python – Is it possible to get a dictionary from a list of lists with concatenated values ​​based on a key match?

Question:

Is it possible from such a structure:

a = [
  [1, [2, 3]],
  [2, [1, 3]], 
  [3, [1, 2]], 
  [1, [5, 6]]
]

get a dictionary of the following form: {1: [2, 3, 5, 6], 2: [1, 3], 3: [1, 2]} ?

Tried it through the usual dict() , but then, if the key already exists, then its last value is taken and it turns out {1: [5, 6], 2: [1, 3], 3: [1, 2]} .

Answer:

from collections import defaultdict

d = defaultdict(list)

for k, v in a:
    d[k].extend(v)
Scroll to Top