0

I'm having trouble modifying my code to add another dictionary to separate "hostNumber" and "hostMode" in my output. Below is the code that found here and manipulated:

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)

resulting in:

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"
                                    }
                                ]
                            }, ...

How can I modify my code to have it output in the following way:

                                ...
                                "sub_hostName": [
                                     {"hostNumber": "1"},
                                     {"hostMode": "WIN"}
                                ]...
clarkus978
  • 574
  • 3
  • 10
  • 22

1 Answers1

0

Use the following line instead of "sub_hostName": [n]:

"sub_hostName": [dict([i]) for i in n.items()]
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36