简体   繁体   English

python从1个平面字典到嵌套字典中提取数据

[英]python extracting data from 1 flat dict to a nested dict

I'm trying write a function that can extract data from a larger dictionary to be put in a smaller nested dict (that will ultimately be a payload in a request). 我正在尝试编写一个函数,该函数可以从较大的字典中提取数据以放入较小的嵌套字典中(最终将成为请求中的有效负载)。 I have just put the payload dict structure with None and the default values with the data to be populated from info_json. 我刚刚将有效载荷dict结构设置为None,并将默认值与要从info_json填充的数据一起使用。 However I get a error "dictionary changed size during iteration" 但是我收到一个错误“字典在迭代过程中更改了大小”

def extract_payload(self, info_json):
        info_dict = json.loads(info_json)
        payload = {"service": None, "current": None,
                   "product1": {"id": None, "id2": None,
                                        "name": None,
                                        "method": "constant_value"},
                   "product2": {"id": None, "id2": None,
                                                "name": None,
                                                "method": None, "always_false": False},
                   "usage": {"usage1": None, "usage2": None, "usage3": None,
                                   "usage4": 2066}

        for key,value in payload.items():
            if value is not None:
                for sub_key in value: 
                    value = info_dict.get(sub_key)
                    payload['sub_key'] = value
            else:
                value = info_dict.get(key)
                payload['key'] = value
        return payload

There is a missing } at the end of payload. 有效内容末尾缺少} You are overwriting payload['sub_key'] the same time for each loop, it needs to be payload[sub_key] , same for else payload[key] = value 您需要为每个循环同时覆盖有效负载['sub_key'],它必须是payload[sub_key]else payload[key] = value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM