python-3.xamazon-web-servicesboto3cloud9-ide

Python3 assigning a value to variable using the index of an object inside a list


I am trying to print all objects inside my array, than ask the user to choose one of the objects. With the input I want to assign that object to an variable. This is what I have so far:

# Call S3 to list current buckets
response = s3.list_buckets()
# Get a list of all bucket names from the response
buckets = [bucket['Name'] for bucket in response['Buckets']]
# Print out the bucket list
print('Bucket List:')
for number, bucket in enumerate(buckets):
    print(f'{number}. {bucket}')

# Which bucket will be used to put object
print('Which bucket should the object be placed?')
test_bucket_name = input('Enter bucket number: ')

I want to get the value from bucket and assign it to test_bucket_name


Solution

  • Explanation commented. This should get you started

    
    import boto3
    
    s3_client = boto3.client('s3')
    
    # Call S3 to list current buckets
    response = s3_client.list_buckets()
    # Get a list of all bucket names from the response
    buckets = [bucket['Name'] for bucket in response['Buckets']]
    # Print out the bucket list
    print('Bucket List:')
    for number, bucket in enumerate(buckets):
        print(f'{number}. {bucket}')
    
    # Which bucket will be used to put object
    print('Which bucket should the object be placed?')
    test_bucket_number = input('Enter bucket number: ') # instead of test_bucket_name, test_bucket_number
    print(test_bucket_number) 
    try:
        # Index the list of buckets with the number they picked, cast to int to make sure their selection was a valid number
        selected_bucket = buckets[int(test_bucket_number)] 
        print(selected_bucket)
    except ValueError as e:
        print(e)
        # Do something to ask the user to pick a number again. Their selection wasn't a number