Generic way to create nested dictionary from flat list in python

后端 未结 3 1260
暗喜
暗喜 2021-01-18 04:48

I am looking for the simplest generic way to convert this python list:

x = [
        {\"foo\":\"A\", \"bar\":\"R\", \"baz\":\"X\"},
                 


        
3条回答
  •  清酒与你
    2021-01-18 05:36

    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.

提交回复
热议问题