## List of Triples to Dict of Dicts

Suppose you (a Pythonic person) have got a list of triples, and you need to convert it to a dict of dicts, where the first two items of a triple are the keys and third item is the value, e. g.:

``l = [(lambda x: (x % 2, x, -x))(x) for x in range(6)]``

This results in: `[(0, 0, 0), (1, 1, -1), (0, 2, -2), (1, 3, -3), (0, 4, -4), (1, 5, -5)]`. And you need something like this: `{0: {0: 0, 2: -2, 4: -4}, 1: {1: -1, 3: -3, 5: -5}}`.

Let’s say you like functional programming. So here is a Haskell-like function that you could write:

``````def mk_2d_dict(triples_list):
"list of triples to 2d-dictionary"
def mk(xs, t):
tk, tv = t[0], t[1:]
if tk in [xk for xk, kv in xs]:
return [(xk, xv) for xk, xv in xs if xk != tk]
+ [(xk, (xv + [tv])) for xk, xv in xs if xk == tk]
else:
return xs + [(tk, [tv])]
return dict((k, dict(v)) for k, v in reduce(mk, triples_list, []))

r = mk_2d_dict(l)
print r, r[1][3]``````

But in fact, if your keys are always used as a pair, then you could combine them into a single key! This leads to a very simple solution:

``````r = dict((x[:-1], x[-1]) for x in l)
print r, r[(1, 3)]``````