Python 2.7:在嵌套字典

时间:2017-07-07 20:43:45

标签: json python-2.7 dictionary

从我的个人主动性开始,结果是一个安静的有趣(我可以说,在某种程度上具有挑战性)项目。我的公司决定淘汰一个产品并用新产品替换它,而不是将数据存储在mdb文件中,而是使用JSON文件。所以我主动创建了一个转换器,它将读取已经创建的mdb文件并将它们转换为新格式的JSON。 但是,现在我正处于这个问题的最后阶段:

我可以读取mdb文件,运行查询以提取特定数据。 通过将targetobj放在FOR LOOP中,我设法为每一行提取数据并输入dict(targetobj)

for val in rows:    
   targetobj={"connection_props": {"port": 7800, "service": "", "host": val.Hostname, "pwd": "", "username": ""},
                        "group_list": val.Groups, "cpu_core_cnt": 2, "target_name": "somename", "target_type": "somethingsamething",
                        "os": val.OS, "rule_list": [], "user_list": val.Users}

如果我将targetobj打印到控制台,我可以清楚地获得每行的所有提取值。

现在,我的任务是将获得的结果(每行)插入主键目标:[] 下的main_dict中。 (请参阅JSON文件样本以供说明)

main_dict = {“changed_time”:0,“年”:0,“描述”:'blahblahblah','目标':[结果来自TARGETOBJ],“启用”:错误}

所以例如我的Json文件应该具有如下结构:

    {"changed_time":1234556,
"year":0,
"description":"blahblahblah",
    "targets":[
                {"group_list":["QA"],
                "cpu_core_cnt":1,
                "target_name":"NewTarget",
                "os":"unix",
                "target_type":"",
                "rule_list":[],
                "user_list":[""],"connection_props":"port":someport,"service":"","host":"host1","pwd":"","username":""}
                }, 
                {"group_list":[],
                "cpu_core_cnt":2,
                "target_name":"",
                "os":"unix",
                "target_type":"",
                "rule_list":[],
                "user_list":["Web2user"],   
                "connection_props":{"port":anotherport,"service":"","host":"host2","pwd":"","username":""}}
                ],
"enabled":false}

到目前为止,我一直在调整,以便按预期编写结果,但每次,我只得到写入的最后一行值。 即:将targetobj作为变量放在目标中:[]

{"changed_time": 0, "year": 0, "description": 'ConvertedConfigFile', 'targets':[targetobj],

我知道我错过了什么,我只需要找到什么,在哪里。 任何帮助将受到高度赞赏。 谢谢

1 个答案:

答案 0 :(得分:0)

首先创建你的main_dict并在你的循环中追加它,即:

main_dict = {"changed_time": 0,
             "year": 0,
             "description": "blahblahblah",
             "targets": [],  # a new list for the target objects
             "enabled": False}

for val in rows:
    main_dict["targets"].append({  # append this dict to the targets list of main_dict
        "connection_props": {
            "port": 7800,
            "service": "",
            "host": val.Hostname,
            "pwd": "",
            "username": ""},
        "group_list": val.Groups,
        "cpu_core_cnt": 2,
        "target_name": "somename",
        "target_type": "somethingsamething",
        "os": val.OS,
        "rule_list": [],
        "user_list": val.Users
    })