【问题标题】:Flattening a list of dicts of lists of dicts (etc) of unknown depth in Python (nightmarish JSON structure)在Python中展平未知深度的字典列表(等)的字典列表(噩梦般的JSON结构)
【发布时间】:2012-01-18 15:18:33
【问题描述】:

我正在处理一个 JSON 结构,它以如下结构输出给我:

[{u'item': u'something',
  u'data': {
            u'other': u'',
            u'else':
               [
                  {
                    u'more': u'even more',
                    u'argh':
                         {
                            ...etc..etc

如您所见,这些是嵌套的字典和列表。 关于递归地展平这些有很多讨论,但我还没有找到一个可以处理字典列表,该列表可能又包含列表的字典、列表的列表、字典的字典等;深度未知!在某些情况下,深度可能高达 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

有什么想法吗?

更新 这非常有效:

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

【问题讨论】:

  • 如果您能向我们提供您想要的那种输出示例,将会很有帮助(举一个非常简单的示例 - 可能只有一两个字典/列表深度)
  • 一个简单的列表就像 [item0, item1, item2...] 是我的目标

标签: python json list recursion dictionary


【解决方案1】:

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

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

我没有测试它,因为您没有提供数据的“有效”sn-p。

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

【讨论】:

  • 尝试用 "".join(filter(None,[path,key])) 替换 "path + "" + key"。这将确保在路径或键为空的情况下不会打印难看的下划线。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 2021-09-07
  • 2014-02-26
  • 2018-07-19
  • 2019-11-04
  • 1970-01-01
  • 2019-01-11
相关资源
最近更新 更多