Home > front end >  filter dictionary (dynamodb insert event)
filter dictionary (dynamodb insert event)

Time:11-18

I want to check if a dynamo db event is INSERT or not. The event looks like this:

{'Records': [{'eventID': '4ff7', 'eventName': 'INSERT', 'eventVersion': '1.1', 'eventSource': 'aws:dynamodb', 'awsRegion': 'eu-central-1', 'dynamodb': {'ApproximateCreationDateTime': 1637232247.0, 'Keys': {'filename': {'S': 'issues.zip'}}, 'NewImage': {'filetype': {'NULL': True}, 'filename': {'S': 'issues.zip'}, 'unixtimestamp': {'S': '1591282803734'}, 'masterclient': {'S': '100-ff0-uat'}, 'source_bucket_name': {'S': 'ems'}, 'filekey': {'S': 'incoming/100-ff0-uat/1591282803734/issues.zip'}}, 'SequenceNumber': '9000', 'SizeBytes': 232, 'StreamViewType': 'NEW_IMAGE'}, 'eventSourceARN': 'arn:aws:dynamodb:eu-central-1:table/filenames-ems/stream/2021-11-18T08:42:01.008'}]}

I was trying this:

if event['Records']['eventName'] == 'INSERT':

but it throws TypeError: list indices must be integers or slices, not str. What's the best way to filter a dictionary inside a list inside a dictionary?

I also tried searching for if value in event.values == 'INSERT'but didnt work either

CodePudding user response:

Since Records contains list of dict, so in order to access eventName you will have to loop through the list first:

Try:

for r in event["Records"]:
    if r['eventName'] == 'INSERT':
        # perform any process
        pass

CodePudding user response:

Records is a list. You can check a specific record with event['Records'][n], where n is the index of the record. Or you can loop through all records to see if there exists a record with 'INSERT'.

events ={'Records': [{'eventID': '4ff7', 'eventName': 'INSERT', 'eventVersion': '1.1', 'eventSource': 'aws:dynamodb', 'awsRegion': 'eu-central-1', 'dynamodb': {'ApproximateCreationDateTime': 1637232247.0, 'Keys': {'filename': {'S': 'issues.zip'}}, 'NewImage': {'filetype': {'NULL': True}, 'filename': {'S': 'issues.zip'}, 'unixtimestamp': {'S': '1591282803734'}, 'masterclient': {'S': '100-ff0-uat'}, 'source_bucket_name': {'S': 'ems'}, 'filekey': {'S': 'incoming/100-ff0-uat/1591282803734/issues.zip'}}, 'SequenceNumber': '9000', 'SizeBytes': 232, 'StreamViewType': 'NEW_IMAGE'}, 'eventSourceARN': 'arn:aws:dynamodb:eu-central-1:table/filenames-ems/stream/2021-11-18T08:42:01.008'}]}

for record in events['Records']:
    if record['eventName'] == 'INSERT':
        #Do something with the record
  • Related