PAYLOAD = {
"data": {
'id': 2,
'rate_service_id': 4,
'max_weight': 4.5,
'max_height': 5,
'max_length': 6.5,
'max_depth': 3,
'fee': 1000
},
"metadata": {
"timestamp": "2022-12-15T06:01:49.645358Z",
"record-type": "data",
"operation": "insert",
"partition-key-type": "primary-key",
"schema-name": "public",
"table-name": "rates",
"transaction-id": 124841932694166
}
}
payload1 = {
'data': {'length': ,
"width": ,
"height": ,
"weight":
},
'metadata': {
"timestamp": ,
"record-type": ,
"operation": ,
"partition-key-type": ,
"schema-name": "",
"table-name": "",
"transaction-id":
}
}
I want to map the keys of PAYLOAD["data] with the keys of payload1["data"] as it have different names. I want to dynamically store the values of key from PAYLOAD to payload1 where (max_length = length , max_width = depth, max_height = height , max_weight = weight) same for metadata also
CodePudding user response:
Modified payload1:
payload1 = {
'data': {"length": "",
"width": "",
"height": "",
"weight":""
},
'metadata': {
"timestamp": "",
"record-type": "",
"operation": "",
"partition-key-type": "",
"schema-name": "",
"table-name": "",
"transaction-id": ""
}
}
Then, you can simply use a dictionary to do this task,
mapping = {'max_length': 'length',
'max_height': 'height',
'max_depth':'width',
'max_weight': 'weight'}
for key, value in PAYLOAD["data"].items():
if key in mapping:
payload1["data"][mapping[key]] = value
mapping = {'timestamp': 'timestamp',
'record-type': 'record-type',
'operation': 'operation',
'partition-key-type': 'partition-key-type',
'schema-name': 'schema-name',
'table-name': 'table-name',
'transaction-id': 'transaction-id'}
for key, value in PAYLOAD["metadata"].items():
if key in mapping:
payload1["metadata"][mapping[key]] = value
print(payload1)
# Output:
#{'data': {'length': 6.5, 'width': 3, 'height': 5, 'weight': 4.5},
# 'metadata': {'timestamp': '2022-12-15T06:01:49.645358Z',
# 'record-type': 'data',
# 'operation': 'insert',
# 'partition-key-type': 'primary-key',
# 'schema-name': 'public',
# 'table-name': 'rates',
# 'transaction-id': 124841932694166}}