【发布时间】:2019-12-27 02:59:50
【问题描述】:
我的数据由多个嵌套的字典和列表组成,我正在尝试将列表转换为字典,其中字典的一个元素内没有嵌套结构。
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(),但我能够接近我想要实现的目标,因为 key_list 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"
}
]
【问题讨论】:
-
欢迎来到 StackOverflow。你能提供一个minimal complete and verifiable example吗?即使它不起作用,它也会显示您尝试的内容。
标签: python json string python-2.7 list