Home > OS >  Unable to add list values to a dictionary - Python3
Unable to add list values to a dictionary - Python3

Time:03-03

I'm trying to create a dictionary in Python with the value's being a list.

For each instance, I'm fetching two tags ( ms_type and name ) and forming a list and appending that list values to each key in the dictionary.

What am I doing wrong ?

Empty dictionary:

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

Output that I'm getting:

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

Desired Output:

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

CODE:

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)

CodePudding user response:

I took your code and cleaned it up a bit:

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)

CodePudding user response:

I don't have credentials to run this so it's untested:

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)

CodePudding user response:

If I were you I would initialize the dictionary values to be empty list so

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

instead of

empty_instance_dict = {k:None for k in instance_id}

Then do

empty_instance_dict[each].append(instance_name)

empty_instance_dict[each].append(ms_type)

When you need to

  • Related