无法将列表值添加到字典中 - Python3

Unable to add list values to a dictionary - Python3

我正在尝试在 Python 中创建一个字典,值是一个列表。

对于每个实例,我获取两个标签(ms_typename)并形成一个列表并将该列表值附加到字典中的每个键。

我做错了什么?

空字典:

{"i-asdasdbuecebwad51": None,"i-0asdasda41bubwadd": None}

我得到的输出:

{'i-asdasdbuecebwad51': None, 'i-0asdasda41bubwadd': None, 10: ['App1', 'service']}

期望输出:

{'i-asdasdbuecebwad51': ['App1', 'service'], 'i-0asdasda41bubwadd': ['App2', 'scheduler']}

代码:

import boto3

instance_id = ["i-asdasdbuecebwad51", "i-0asdasda41bubwadd"]


def get_inst_name(connection, instance_id):
    print("We are in the get inst name function")
    try:
        empty_instance_dict = {k: None for k in instance_id}
        print(f"Dictionary Initiated {empty_instance_dict}")
        print("------\n")
        for each in instance_id:
            empty = []
            for_response = (connection.describe_tags(
                Filters=[
                    {
                        'Name': 'resource-id',
                        'Values': [each, ],
                    },
                ],
            )
            )
            for each in range(0, len(for_response['Tags'])):
                if for_response['Tags'][each]['Key'] == "ms_type":
                    microservice_types = for_response['Tags'][each]['Value']
                    break

            for each in range(0, len(for_response['Tags'])):
                if for_response['Tags'][each]['Key'] == "Name":
                    instance_name = for_response['Tags'][each]['Value']
                    break

            empty.append(instance_name)
            empty.append(ms_type)

            empty_instance_dict[each] = empty
        return empty_instance_dict

    except Exception as e:
        print(f"The instance {instance_id} doesn't have the tag called name")
        return None


def lambda_handler(instance_id):
    aws_region = "us-east-1"
    print(type(instance_id))
    print("Instance found are:")
    print(instance_id)
    ec2client = boto3.client('ec2', region_name=aws_region)
    print("Fetching instance name:")
    instance_name = get_inst_name(ec2client, instance_id)
    ### 
    print(type(instance_name))
    print(instance_name)


lambda_handler(instance_id)

如果我是你,我会将字典值初始化为空列表,所以

empty_instance_dict = {k:[] for k in instance_id}

而不是

empty_instance_dict = {k:None for k in instance_id}

然后做

empty_instance_dict[each].append(instance_name)

empty_instance_dict[each].append(ms_type)

当你需要的时候

我没有 运行 的凭据,因此未经测试:

import boto3

client = boto3.client('ec2', region_name='us-east-1')

output = {}

for instance in ['i-asdasdbuecebwad51', 'i-0asdasda41bubwadd']:
    filter_ = {'Name': 'resource-id', 'Values': [instance]}
    for tag in client.describe_tags(Filters=[filter_])['Tags']:
        if (key := tag[instance]['Key']) in ['ms_type', 'Name']:
            output.setdefault(instance, []).append(key)

print(output)

我把你的代码整理了一下:

import boto3

instance_id = ["i-asdasdbuecebwad51","i-0asdasda41bubwadd"]
result = {}

ec2_client = boto3.client('ec2')

response = ec2_client.describe_instances(InstanceIds=instance_list)

for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        instance_id = instance['InstanceId']
        tags = [tag['Value'] for tag in instance['Tags'] if tag['Key'] in ['ms_type', 'Name']]
        result[instance_id] = tags

print(result)