英文:
list indices must be integers or slices, not str when parsing DynamoDB payload
问题
我是新手使用 DynamoDB,所以一直在努力找出可能出错的地方。我有这个查询,想要解析返回的有效载荷,但一直得到以下错误信息:
列表索引必须是整数或切片,而不是字符串
以下是查询代码:
def get_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('未找到男性性别')
return []
def valid_male_adult(payload):
return payload['age'] > 17 and payload['gender'] == 'Male'
# 尝试以以下方式运行它
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)
它一直显示列表索引必须是整数或切片,而不是字符串的错误信息。
任何帮助将不胜感激。我尝试打印它,但除了错误消息之外什么都不显示。它没有指出错误可能在哪里,以便我修复。
英文:
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.
答案1
得分: 0
你的 `list_of_adults` 是一个列表的列表,这破坏了你的逻辑。
将 `items.append(response['Items'])` 更改为:
items = items + response['Items']
英文:
Your list_of_adults
is a list of lists, which is breaking your logic.
Change items.append(response['Items'])
to:
items = items + response['Items']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论