Python 以特定格式输出字典列表

Python output list of dictionary in specific format

您好,我是 python 的新手,这可能是一件小事,但我发现很难获得特定格式的输出。

我有以下正在返回的字典列表

vpcs = [{'ResourceOwnerId': '111111111111', 'ResourceType': 'vpc', 'ResourceId': 'vpc-aaaaa'},
        {'ResourceOwnerId': '222222222222', 'ResourceType': 'vpc', 'ResourceId': 'vpc-ccccc'}
        {'ResourceOwnerId': '111111111111', 'ResourceType': 'vpc', 'ResourceId': 'vpc-ddddd'}]

下面是我的脚本片段

for vpc in vpcs:
        acc_data = {
            "account_number": vpc["ResourceOwnerId"],
            "vpc": [vpc['ResourceId']]
        }
        acc_list.append(acc_data)

print(acc_list)

输出结果如下

        [
            {'account_number': '111111111111', 'vpc': ['vpc-aaaaa']},
            {'account_number': '222222222222', 'vpc': ['vpc-ccccc']},
            {'account_number': '111111111111', 'vpc': ['vpc-ddddd']}
        ]

而我想要这样的输出

        [
            {'account_number': '111111111111', 'vpc': ['vpc-aaaaa', 'vpc-ddddd']},
            {'account_number': '222222222222', 'vpc': ['vpc-ccccc']}
        ]

即“account_number”与那些 vpc 相同,应该附加而不是创建新条目。任何帮助将不胜感激谢谢

分两个阶段进行。使用字典构建唯一列表,然后转换为字典列表:

from collections import defaultdict

vpcs = [{'ResourceOwnerId': '111111111111', 'ResourceType': 'vpc', 'ResourceId': 'vpc-aaaaa'},
        {'ResourceOwnerId': '222222222222', 'ResourceType': 'vpc', 'ResourceId': 'vpc-ccccc'},
        {'ResourceOwnerId': '111111111111', 'ResourceType': 'vpc', 'ResourceId': 'vpc-ddddd'}]

accum = defaultdict(list)
for vpc in vpcs:
    accum[vpc['ResourceOwnerId']].append( vpc['ResourceId'] )

print(accum)

acc_list = []
for k, v in accum.items():
    acc_list.append(
        {
            "account_number": k,
            "vpc": v
        }
    )

print(acc_list)

输出:

defaultdict(<class 'list'>, {'111111111111': ['vpc-aaaaa', 'vpc-ddddd'], '222222222222': ['vpc-ccccc']})
[{'account_number': '111111111111', 'vpc': ['vpc-aaaaa', 'vpc-ddddd']}, {'account_number': '222222222222', 'vpc': ['vpc-ccccc']}]

或者,喜欢one-liners的人:

...
acc_list = [ { "account_number": k, "vpc": v } for k, v in accum.items()]
print(acc_list)

您可以使用 dict.setdefault 来创建基本的 sub-dicts,当第一次看到密钥时,列表为空。然后只是追加。结果将在 dict.values():

vpcs = [{'ResourceOwnerId': '111111111111', 'ResourceType': 'vpc', 'ResourceId': 'vpc-aaaaa'},
        {'ResourceOwnerId': '222222222222', 'ResourceType': 'vpc', 'ResourceId': 'vpc-ccccc'},
        {'ResourceOwnerId': '111111111111', 'ResourceType': 'vpc', 'ResourceId': 'vpc-ddddd'}]

groups = {}

for d in vpcs:
    k = d['ResourceOwnerId']
    groups.setdefault(k, {'account_number':k, 'vpc':[]} )['vpc'].append(d['ResourceId'])
    
list(groups.values())

这会给你:

[{'account_number': '111111111111', 'vpc': ['vpc-aaaaa', 'vpc-ddddd']},
 {'account_number': '222222222222', 'vpc': ['vpc-ccccc']}]
    from copy import deepcopy # create a copy of a list.
    # Your code snippet
    for vpc in vpcs:
        acc_data = {
            "account_number": vpc["ResourceOwnerId"],
            "vpc": [vpc['ResourceId']]
        }
        acc_list.append(acc_data)

    # Add this
    new_acc_list = deepcopy(acc_list)
    previous_acc_numbers = {} # int: index

    for acc_data in acc_list:
        acc_number, acc_vpc = acc_data.get(account_number), acc_data.get("vpc")
        if acc_number in previous_acc_numbers:
            new_acc_list[previous_acc_numbers.get(acc_number)].get("vpc").append(acc_data.get("vpc"))
    
    print(acc_list)

尝试创建字典映射帐号到 vpc。然后改造这个字典:

dct = dict()
for vpc in vpcs:
    if vpc["ResourceOwnerId"] not in dct:
        dct[vpc["ResourceOwnerId"]] = list()
    dct[vpc["ResourceOwnerId"]].append(vpc["ResourceId"])

output = [{"account_number": k, "vpc": v} for k,v in dct.items()]

>>> output
[{'account_number': '111111111111', 'vpc': ['vpc-aaaaa', 'vpc-ddddd']},
 {'account_number': '222222222222', 'vpc': ['vpc-ccccc']}]