I am looking for the simplest generic way to convert this python list:
x = [
{\"foo\":\"A\", \"bar\":\"R\", \"baz\":\"X\"},
I would define a function that performs a single grouping step like this:
from itertools import groupby
def group(items, key, subs_name):
return [{
key: g,
subs_name: [dict((k, v) for k, v in s.iteritems() if k != key)
for s in sub]
} for g, sub in groupby(sorted(items, key=lambda item: item[key]),
lambda item: item[key])]
and then do
[{'foo': g['foo'], 'bars': group(g['bars'], "bar", "bazs")} for g in group(x,
"foo", "bars")]
which gives the desired result for foos
.