我无法修改代码以添加另一个字典来分隔输出中的"hostNumber"
和"hostMode"
。以下是找到here并进行操作的代码:
import json
from json import dumps
top = "Top_Level"
top_dict = {}
top_dict["name"] = top
top_dict["sub_name"] = []
for site, site_data in df.groupby("site", sort=False):
site_dict = {}
site_dict["site"] = site
site_dict["sub_site"] = []
for stor, stor_data in site_data.groupby("system", sort=False):
stor_dict = {}
stor_dict["system"] = stor
stor_dict["sub_system"] = []
for port, port_data in stor_data.groupby("portId", sort=False):
port_dict = {}
port_dict["portId"] = port
port_dict["sub_portId"] = []
for host, host_data in port_data.groupby("hostName", sort=False):
host_data = host_data.drop(["portId", "system",
"site"], axis=1).set_index(
"hostName")
for n in host_data.to_dict(orient="records"):
port_dict["sub_portId"].append({"hostName": host,
"sub_hostName": [n]})
stor_dict["sub_system"].append(port_dict)
site_dict["sub_site"].append(stor_dict)
top_dict["sub_name"].append(site_dict)
top_out = dumps(top_dict)
parsed = json.loads(top_out)
导致:
print(json.dumps(parsed, indent=4, sort_keys=True))
{
"name": "Top_Level",
"sub_name": [
{
"site": "A",
"sub_site": [
{
"system": "system01",
"sub_system": [
{
"portId": "1-A",
"sub_portId": [
{
"hostName": "ahost005",
"sub_hostName": [
{
"hostNumber": "1",
"hostMode": "WIN"
}
]
}, ...
如何修改我的代码以便按以下方式输出:
...
"sub_hostName": [
{"hostNumber": "1"},
{"hostMode": "WIN"}
]...
答案 0 :(得分:0)
使用以下行代替"sub_hostName": [n]
:
"sub_hostName": [dict([i]) for i in n.items()]