拼合带有嵌套键和数组的字典

时间:2019-10-22 09:56:12

标签: python-3.x dictionary

我需要有关以以下格式展平嵌套字典的功能的帮助:

dict_test = {
    "subdoc": {
        "a": 1,
        "b": 2,
        "c": 3,
        "array": [
            {"name": "elmo"},
            {"name": "oscar"}
        ]
    }
}

我尝试了下面的函数,但是并没有使数组元素内的嵌套键变平。

def flatten_dict(dd, separator='.', prefix=''):
    return { prefix + separator + k if prefix else k : v
             for kk, vv in dd.items()
             for k, v in flatten_dict(vv, separator, kk).items()
             } if isinstance(dd, dict) else { prefix : dd }

我当前的输出是:

{'subdoc.a': 1,
 'subdoc.b': 2,
 'subdoc.c': 3,
 'subdoc.array': [{'name': 'elmo'}, {'name': 'oscar'}]}

但是实际上我看起来是这样的:

{
    "subdoc.a": 1,
    "subdoc.b": 2,
    "subdoc.c": 3,
    "subdoc.array.0.name": "elmo",
    "subdoc.array.1.name": "oscar"
}

1 个答案:

答案 0 :(得分:1)

dict_test = {
    "subdoc": {
        "a": 1,
        "b": 2,
        "c": 3,
        "array": [
            {"name": "elmo"},
            {"name": "oscar"}
        ]
    }
}

def flatten(d):
    agg = {}
    def _flatten(d, prev_key=''):
        if isinstance(d, list):
            for i, item in enumerate(d):
                new_k = '%s.%s' % (prev_key, i) if prev_key else i
                _flatten(item, prev_key=new_k)
        elif isinstance(d, dict):
            for k, v in d.items():
                new_k = '%s.%s' % (prev_key, k) if prev_key else k
                _flatten(v, prev_key=new_k)
        else:
            agg[prev_key] = d

    _flatten(d)
    return agg


print(flatten(dict_test))
# gives {'subdoc.a': 1, 'subdoc.b': 2, 'subdoc.c': 3, 'subdoc.array.0.name': 'elmo', 'subdoc.array.1.name': 'oscar'}

注意:仅针对您的情况进行了测试