在Python中扁平化未知深度的词典(等)列表的列表(噩梦般的JSON结构)

Lit*_*les 6 python recursion json dictionary list

我正在处理一个JSON结构,它以这样的结构输出给我:

[{u'item': u'something',
  u'data': {
            u'other': u'',
            u'else':
               [
                  {
                    u'more': u'even more',
                    u'argh':
                         {
                            ...etc..etc
Run Code Online (Sandbox Code Playgroud)

如您所见,这些是嵌套的dicts和列表.有很多关于递归地扁平这些的讨论,但是我还没有找到一个可以处理字典列表的字典,这些字典又可以包含列表字典,列表列表,字典字典等; 深度不详!在某些情况下,深度可能高达100左右.到目前为止我一直在尝试这个没有太多运气(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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

更新 这几乎是有效的:

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
Run Code Online (Sandbox Code Playgroud)

jsb*_*eno 11

由于数据的深度是任意的,因此更容易使用递归来展平它.此函数创建一个平面字典,其中每个数据项的路径都作为键组成,以避免冲突.

例如,您可以稍后检索其内容for key in sorted(dic_.keys()).

我没有测试它,因为你没有提供数据的"有效"片段.

def flatten(structure, key="", path="", flattened=None):
    if flattened is None:
        flattened = {}
    if type(structure) not in(dict, list):
        flattened[((path + "_") if path else "") + key] = structure
    elif isinstance(structure, list):
        for i, item in enumerate(structure):
            flatten(item, "%d" % i, path + "_" + key, flattened)
    else:
        for new_key, value in structure.items():
            flatten(value, new_key, path + "_" + key, flattened)
    return flattened
Run Code Online (Sandbox Code Playgroud)