将嵌套字典展平为键和连接的字符串值 [英] Flatten nested dictionary to key and joined string value

查看:99
本文介绍了将嵌套字典展平为键和连接的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help with a function to flatten a nested dictionary in the following format:

dict_test = {
    "id" : "5d4c2c0fd89234260ec81",
    "Reference Number" : "JA-L800D-191",
    "entities_discovered" : {
        "OTHER_ID" : [ 
            "L800DFAG02191"
        ],
        "CODE_ID" : [ 
            "160472708",
            "276954773"
        ]
    },
    "label_field" : [ 
        "ELECTRONICS",
        "HDMI"
    ],
    "numeric_field" : [ 
        491, 
        492
    ],

}

我正在使用的函数将字典按我的意愿展平到一个维度(键:值),但是没有在相同的键迭代中将这些值连接在一起.

The function I was working with, flattens the dictionary to one dimension (key:value) as I want, but doesn´t join the values within the same key iteration.

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

我当前的输出是:

{
    "id" : "5d4c2c0fd89234260ec81",
    "Reference Number" : "JA-L800D-191",
    "entities_discovered.OTHER_ID.0" : "L800DFAG02191",
    "entities_discovered.CODE_ID.0" : "160472708",
    "entities_discovered.CODE_ID.1" : "276954773",
    "label_field.0" : "ELECTRONICS",
    "label_field.1" : "HDMI",
    "numeric_field.0" : 491, 
    "numeric_field.1" : 492
}

但是实际上我正在寻找类似的东西(将值连接到相同的字符串中,并用或|分隔):

But actually I´m looking for something like (joining the values into the same string and separated by , or |):

{
    "id" : "5d4c2c0fd89234260ec81",
    "Reference Number" : "JA-L800D-191",
    "OTHER_ID" : "L800DFAG02191",
    "CODE_ID" : "160472708, 276954773",
    "label_field" : "ELECTRONICS, HDMI",
    "numeric_field" : ¨491, 492¨
}

推荐答案

您可以使用join()内置方法将值连接在一起.

You can use join() built-in method to join values together.

def do():
    dict_test = {
        "id": "5d4c2c0fd89234260ec81",
        "Reference Number": "JA-L800D-191",
        "entities_discovered": {
            "OTHER_ID": [
                "L800DFAG02191"
            ],
            "CODE_ID": [
                "160472708",
                "276954773"
            ]
        },
        "label_field": [
            "ELECTRONICS",
            "HDMI"
        ],
        "numeric_field": [
            491,
            492
        ],
    }

    new_dict = {}
    for key, value in dict_test.items():
        if isinstance(value, dict):
            for _key, _value in value.items():
                if isinstance(_value, list):
                    new_dict.update({_key: ', '.join([str(item) for item in _value])})

        elif isinstance(value, list):
            new_dict.update({key: ', '.join([str(item) for item in value])})

        else:
            new_dict.update({key: value})

    return new_dict


if __name__ == '__main__':
    print(do())

输出:

{
    'id': '5d4c2c0fd89234260ec81',
    'Reference Number': 'JA-L800D-191',
    'OTHER_ID': 'L800DFAG02191',
    'CODE_ID': '160472708, 276954773',
    'label_field': 'ELECTRONICS, HDMI',
    'numeric_field': '491, 492'
}

这篇关于将嵌套字典展平为键和连接的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆