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

时间:2016-03-29 21:20:27

标签: python

我正在尝试编写一个函数,该函数可以从较大的字典中提取数据,以便放入较小的嵌套字典中(最终将成为请求中的有效负载)。 我刚刚将有效负载dict结构设置为None,默认值包含要从info_json填充的数据。但是我在迭代期间得到了一个错误"字典改变了大小"

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

1 个答案:

答案 0 :(得分:1)

有效负载末尾缺少}。您为每个循环同时覆盖有效负载[' sub_key'],它必须为payload[sub_key]else payload[key] = value

相同