List of Triples to Dict of Dicts

2007-09-03 at 04:45 | Posted in devel, fun, lang:en, think | Leave a comment

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]
      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)]

So think twice about your domain before starting to program! ;)


Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at
Entries and comments feeds.

%d bloggers like this: