无法创建 python 字典是特定格式

Unable to create python dictionary is specific format

我有以下数据:

        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'}]}

我想创建一个类似这样的帐户地图

        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"]}
        }

这样如果我 a['11111111111']['eu-west-1'] 输出应该是 ["dxcon-ff"].

这样就可以了,

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)

输出-

{'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']}}

试试这个:

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'])

结果:

{
    '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']