如何判断DynamoDB事件为INSERT类型及过滤嵌套字典列表结构
问题原因分析
你之前的写法报错TypeError: list indices must be integers or slices, not str,核心原因是event['Records']返回的是列表类型,列表无法直接用字符串作为索引取值,必须先指定列表下标,或者遍历所有列表元素再取字典字段。
解决方法
场景1:确认每次事件仅包含1条记录
直接取列表第一个元素的eventName字段判断即可:
if event['Records'][0]['eventName'] == 'INSERT': # 你的业务逻辑
场景2:事件可能包含多条记录(推荐写法)
DynamoDB流触发函数时默认会批量传递事件,最多可包含100条记录,建议遍历所有记录处理避免遗漏:
for record in event['Records']: if record['eventName'] == 'INSERT': # INSERT事件对应的业务逻辑 pass
更严谨的兼容写法
为了避免键不存在、列表为空等异常场景导致程序报错,可以增加判空逻辑:
# 先校验Records字段存在且为非空列表 if 'Records' in event and isinstance(event['Records'], list) and len(event['Records']) > 0: for record in event['Records']: # 用get方法取值,不存在eventName字段时也不会抛出异常 if record.get('eventName') == 'INSERT': # 业务逻辑 pass
嵌套结构取值通用思路
遇到字典嵌套列表再嵌套字典的结构时,逐层确认每一层的类型再处理即可:
- 若当前层是字典:用
[key]或者get(key)方法取值 - 若当前层是列表:先指定下标取对应元素,或者遍历所有元素再处理后续字段
内容的提问来源于stack exchange,提问作者user13067694
相关产品推荐
相关产品推荐

