I am dealing with a JSON structure, which is displayed to me in such structures:
[{u'item': u'something',
u'data': {
u'other': u'',
u'else':
[
{
u'more': u'even more',
u'argh':
{
...etc..etc
As you can see, these are nested dicts and lists. There are many discussions about smoothing these out recursively, but I have not yet found one that can deal with a list of dictionaries, which, in turn, can contain either list dictionaries, list lists, dictionary dictionaries, etc .; which have an unknown depth! In some cases, the depth can be up to 100 or so. I have tried this so far without much luck (python 2.7.2):
def flatten(structure):
out = []
for item in structure:
if isinstance(item, (list, tuple)):
out.extend(flatten(item))
if isinstance(item, (dict)):
for dictkey in item.keys():
out.extend(flatten(item[dictkey]))
else:
out.append(item)
return out
Any ideas?
UPDATE
This pretty much works:
def flatten(l):
out = []
if isinstance(l, (list, tuple)):
for item in l:
out.extend(flatten(item))
elif isinstance(l, (dict)):
for dictkey in l.keys():
out.extend(flatten(l[dictkey]))
elif isinstance(l, (str, int, unicode)):
out.append(l)
return out
source
share