将嵌套结构转换为字符串

2024-09-28 05:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据由多个嵌套的dict和list组成,我正在尝试将list转换为一个dictionary,其中dictionary的一个元素中没有嵌套结构。你知道吗

data = [
    [
        u'abc', u'1.2.3.4', 52, 
        [u'prod', u'linux'], 
        u'jack',
        [u'2019-08-15', u'2019-06-10'],  
        {u'dc': u'NA', u'network': u'public'}
    ], 
    [
        u'xyz', u'127.0.0.1', 126, 
        [u'prod', u'linux', u'backup'], 
        u'rich', 
        [u'2019-03-21', u'2019-05-01'], 
        {u'network': u'public', u'owner': u'security team'}
    ],
    [
        u'pqr', u'5.6.7.8', 125,  
        [u'stage', u'ubuntu'],
         u'kevin', 
         [], 
        {u'newtwork': u'private', u'type': u'sql', u'owner': u'security team'}
    ]
]

key_list = ['hostname', 'ip_address', 'num_process', 'usage', 'user', 'restarts', 'tags']

我试着使用zip(),但是我能够接近我想要实现的目标,因为键列表中的最后一个元素tags一直困扰着我。 我看到了这一页 Convert the nested json into a dictionary format with no nested objects

这给了我希望,但后来我发现在这个解决方案中,数据只有一个嵌套列表,所以这种方法是很好的,但我的数据有多个嵌套列表,而且在将来还会增加。你知道吗

我如何完善代码,以便将来如果数据中出现新的列表,解决方案不会受到影响。你知道吗

[
    {
        "hostname":"abc",
        "ip_address":"1.2.3.4",
        "num_process":"52",
        "usage":"prod, linux",
        "owner":"jack",
        "restarts":"2019-08-15, 2019-06-10",
        "dc":"NA",
        "network":"public"
    },
    {
    "hostname":"xyz",
    "ip_address":"127.0.0.1",
    "num_process":"126",
    "usage":"prod, linux,backup",
    "user":"rich",
    "restarts":"2019-03-21, 2019-05-01",
    "owner":"security team",
    "network":"public"
    },
    {
        "hostname":"pqr",
        "ip_address":"5.6.7.8",
        "num_process":"125",
        "usage":"stage, ubuntu",
        "owner":"kevin",
        "restarts":"",
        "user":"security team",
        "newtwork":"private",
        "type":"sql"
    }
]

Tags: 数据ipaddresslinuxusageprodnetworkpublic
1条回答
网友
1楼 · 发布于 2024-09-28 05:17:45

试试这个:

def get_mapping(data, keys):
    for entry in data:
        result = dict(zip(key_list, (value for value in entry if not isinstance(value, dict))))
        for value in entry:
            if isinstance(value, dict):
                result.update(value)
        yield result

list(get_mapping(data, key_list))

输出:

[{'hostname': 'abc',
  'ip_address': '1.2.3.4',
  'num_process': 52,
  'usage': ['prod', 'linux'],
  'user': 'jack',
  'restarts': ['2019-08-15', '2019-06-10'],
  'dc': 'NA',
  'network': 'public'},
 {'hostname': 'xyz',
  'ip_address': '127.0.0.1',
  'num_process': 126,
  'usage': ['prod', 'linux', 'backup'],
  'user': 'rich',
  'restarts': ['2019-03-21', '2019-05-01'],
  'network': 'public',
  'owner': 'security team'},
 {'hostname': 'pqr',
  'ip_address': '5.6.7.8',
  'num_process': 125,
  'usage': ['stage', 'ubuntu'],
  'user': 'kevin',
  'restarts': [],
  'newtwork': 'private',
  'type': 'sql',
  'owner': 'security team'}]

相关问题 更多 >

    热门问题