Search This Blog

Tuesday, September 24, 2019

Python - Map Nested Map

Input

[{
"groupId": "a1",
"orderId": "b1"
}, {
"groupId": "a2",
"orderId": "b2"
}, {
"groupId": "a2",
"orderId": "b3"
}]

Output 
{
'a1': {
'b1': {
'groupId': 'a1',
'orderId': 'b1'
}
},
'a2': {
'b2': {
'groupId': 'a2',
'orderId': 'b2'
},
'b3': {
'groupId': 'a2',
'orderId': 'b3'
}
}
}


Code

data = [{"groupId":"a1","orderId":"b1"},{"groupId":"a2","orderId":"b2"}, {"groupId":"a2","orderId":"b3"}]

groupMap = {}


for x in data:
    if ( helpers.isKeyExists (groupMap, x['groupId']) == False ):
        orderMap = {}
        orderMap[x['orderId']] = x;
        groupMap[x['groupId']] = orderMap;
    else:
        tempOrderMap = {}
        #if ( helpers.isKeyExists (orderMap, x['groupId']) == False ):
        tempOrderMap = groupMap[x['groupId']]
        tempOrderMap[x['orderId']] = x;
        groupMap[x['groupId']] = tempOrderMap;
       

print (groupMap);


No comments:

Hit Counter


View My Stats