I have the following data:
response = {'connections': [{'ownerAccount': '11111111111', 'connectionId': 'dxcon-ff', 'region': 'eu-west-1'},
{'ownerAccount': '11111111111', 'connectionId': 'dxcon-pl', 'region': 'eu-west-2'},
{'ownerAccount': '11111111111', 'connectionId': 'dxcon-123', 'region': 'eu-west-2'},
{'ownerAccount': '222222222222', 'connectionId': 'dxcon-51', 'region': 'us-east-1'},
{'ownerAccount': '222222222222', 'connectionId': 'dxcon-1i', 'region': 'us-east-2'},
{'ownerAccount': '333333333333', 'connectionId': 'dxcon-511i', 'region': 'eu-west-1'}]}
I want to create a map of accounts something like this
a = {
"11111111111" = {"eu-west-1": ["dxcon-ff"], "eu-west-2": ["dxcon-pl", "dxcon-123"]},
"222222222222" = {"us-east-1": ["dxcon-51"], "us-east-2": ["dxcon-1i"]},
"333333333333" = {"eu-west-1": ["dxcon-511i"]}
}
Such that if I do a['11111111111']['eu-west-1']
output should be ["dxcon-ff"]
.
CodePudding user response:
This does the job,
mydict = {}
for connection in response["connections"]:
owner = connection["ownerAccount"]
if owner not in mydict:
mydict[owner] = {}
mydict[owner][connection["region"]] = []
mydict[owner][connection["region"]].append(connection["connectionId"])
print(mydict)
Output -
{'11111111111': {'eu-west-1': ['dxcon-ff'], 'eu-west-2': ['dxcon-123']},
'222222222222': {'us-east-1': ['dxcon-51'], 'us-east-2': ['dxcon-1i']},
'333333333333': {'eu-west-1': ['dxcon-511i']}}
CodePudding user response:
Try this:
data = {'connections': [
{'ownerAccount': '11111111111', 'connectionId': 'dxcon-ff', 'region': 'eu-west-1'},
{'ownerAccount': '11111111111', 'connectionId': 'dxcon-pl', 'region': 'eu-west-2'},
{'ownerAccount': '11111111111', 'connectionId': 'dxcon-123', 'region': 'eu-west-2'},
{'ownerAccount': '222222222222', 'connectionId': 'dxcon-51', 'region': 'us-east-1'},
{'ownerAccount': '222222222222', 'connectionId': 'dxcon-1i', 'region': 'us-east-2'},
{'ownerAccount': '333333333333', 'connectionId': 'dxcon-511i', 'region': 'eu-west-1'}]}
a = {}
for d in data['connections']:
key = d['ownerAccount']
region = d['region']
conId = d['connectionId']
if key not in a.keys():
a[key] = {}
if region not in a[key].keys():
a[key][region]= []
a[key][region].append(conId)
print(a)
print(a['11111111111']['eu-west-1'])
Result:
{
'11111111111': {'eu-west-1': ['dxcon-ff'], 'eu-west-2': ['dxcon-pl', 'dxcon-123']},
'222222222222': {'us-east-1': ['dxcon-51'], 'us-east-2': ['dxcon-1i']},
'333333333333': {'eu-west-1': ['dxcon-511i']}
}
['dxcon-ff']