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.
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'}.
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.
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.
#!/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With