Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to create nested dictionary from flat list in python

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

x = [
        {"foo":"A", "bar":"R", "baz":"X"},
        {"foo":"A", "bar":"R", "baz":"Y"},
        {"foo":"B", "bar":"S", "baz":"X"},
        {"foo":"A", "bar":"S", "baz":"Y"},
        {"foo":"C", "bar":"R", "baz":"Y"},
    ]

into:

foos = [ 
         {"foo":"A", "bars":[
                               {"bar":"R", "bazs":[ {"baz":"X"},{"baz":"Y"} ] },
                               {"bar":"S", "bazs":[ {"baz":"Y"} ] },
                            ]
         },
         {"foo":"B", "bars":[
                               {"bar":"S", "bazs":[ {"baz":"X"} ] },
                            ]
         },
         {"foo":"C", "bars":[
                               {"bar":"R", "bazs":[ {"baz":"Y"} ] },
                            ]
         },
      ]

The combination "foo","bar","baz" is unique, and as you can see the list is not necessarily ordered by this key.

like image 800
RickyA Avatar asked Jan 03 '12 11:01

RickyA


People also ask

How do you make a nested dictionary in Python?

Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.

Can you nest a dictionary in a list Python?

You can have dicts inside of a list. The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.

How are the nested dictionaries created?

You can create a nested dictionary in Python by placing comma-separated dictionaries within curly braces {}. A Python nested dictionary allows you to store and access data using the key-value mapping structure within an existing dictionary.


1 Answers

#!/usr/bin/env python3
from itertools import groupby
from pprint import pprint

x = [
        {"foo":"A", "bar":"R", "baz":"X"},
        {"foo":"A", "bar":"R", "baz":"Y"},
        {"foo":"B", "bar":"S", "baz":"X"},
        {"foo":"A", "bar":"S", "baz":"Y"},
        {"foo":"C", "bar":"R", "baz":"Y"},
    ]


def fun(x, l):
    ks = ['foo', 'bar', 'baz']
    kn = ks[l]
    kk = lambda i:i[kn]
    for k,g in groupby(sorted(x, key=kk), key=kk):
        kg = [dict((k,v) for k,v in i.items() if k!=kn) for i in g]
        d = {}
        d[kn] = k
        if l<len(ks)-1:
            d[ks[l+1]+'s'] = list(fun(kg, l+1))
        yield d

pprint(list(fun(x, 0)))

[{'bars': [{'bar': 'R', 'bazs': [{'baz': 'X'}, {'baz': 'Y'}]},
           {'bar': 'S', 'bazs': [{'baz': 'Y'}]}],
  'foo': 'A'},
 {'bars': [{'bar': 'S', 'bazs': [{'baz': 'X'}]}], 'foo': 'B'},
 {'bars': [{'bar': 'R', 'bazs': [{'baz': 'Y'}]}], 'foo': 'C'}]

note: dict is unordered! but it's the same as yours.

like image 72
kev Avatar answered Sep 25 '22 21:09

kev