2017-06-22 148 views
0

我在修改我的代碼時添加了另一個字典,以便在我的輸出中分隔"hostNumber""hostMode"時遇到問題。下面是發現here和操作的代碼:造成熊貓在深嵌套JSON內創建字典

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

使用下面一行代替"sub_hostName": [n]

"sub_hostName": [dict([i]) for i in n.items()]