0

I want to build a dict in python from a list, the key of the dict is the first column and the value of the map is the second column. Is there any elegant way to implement this?

For example, A= [[1,2], [1,3], [2,3]] The result is M={1:[2,3],2:[3]} My own way is for row in A: if row[0] not in M: M[row[0]] = [] M[row[0]].append(row[1]) Is there any better solution? Functional Programming methods are preferred.

maple
  • 1,828
  • 2
  • 19
  • 28
  • 1
    Use the zip function. https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python – codeslord Dec 08 '17 at 04:11

2 Answers2

3

One way to do this is with a defaultdict

from collections import defaultdict

A= [[1,2], [1,3], [2,3]]
d = defaultdict(list)
for k, v in A:
    d[k].append(v)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
2

You can use setdefault:

A= [[1,2], [1,3], [2,3]]
M = {}                                                                 
for k,v in A:
    M.setdefault(k, []).append(v)

M 
# {1: [2, 3], 2: [3]}

If it must be functional (Disclaimer: wasteful, not recommended):

import operator, itertools
grps = itertools.groupby(sorted(A, key=operator.itemgetter(0)), operator.itemgetter(0))
M = {k: list(map(operator.itemgetter(1), v)) for k, v in grps}
M
# {1: [2, 3], 2: [3]}
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99