Search code examples
python-3.xamazon-dynamodbdynamodb-queries

list indices must be integers or slices, not str when parsing DynamoDB payload


I am new to DynamoDB, so been struggling to workout what I may be doing wrong. I have this query and want to parse the returned payload, but I keep getting

list indices must be integers or slices, not str

Here is the query:

def get_males():
    """ Searches all males """   

    response = table.query(
        IndexName='gender-index',
        KeyConditionExpression=Key('gender').eq('Male')
    )
    if response['Count'] > 0:
        items = response['Items']
        if 'LastEvaluatedKey' in response:
            while 'LastEvaluatedKey' in response:
                response = table.query(
                    ExclusiveStartKey=response['LastEvaluatedKey'],
                    IndexName='state-index',
                    KeyConditionExpression=Key('gender').eq('Male')
                )
                items.append(response['Items'])
        return items
    else:
        logger.info('No males genders found')
        return []


def valid_male_adult(payload):    
    return payload['age'] > 17 and payload['gender'] == 'Male'


#tried running it like this

if __name__ == "__main__":

    list_of_adults = []
    adults = get_males()
    for adult in adults:
        if valid_male_adult(adult):
            list_of_adults.append(adult)
    
    json.dumps(list_of_adults[1],cls=DecimalEncoder)       

It just keeps saying list indices must be integers or slices, not str

Any help will be appreciated.

I have tried printing it, but nothing shows other than the error message. It's not pointing to where the error might be for me to fix.


Solution

  • Your list_of_adults is a list of lists, which is breaking your logic.

    Change items.append(response['Items']) to:

    items = items + response['Items']