Reputation: 7458
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. 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
Upvotes: 0
Views: 97
Reputation: 10058
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
Upvotes: 1