key error lambda function dynamodb

0

Hi,

I am getting the following error when testing a lambda function which exports fields from a dynamodb if they are populated :

"errorMessage": "'Win'", "errorType": "KeyError",

The lambda function is:


import boto3

def lambda_handler(event, context): # Connect to DynamoDB dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('ticketing')

# Get all items from the table
items = table.scan()['Items']

# Create a list to hold the filtered items
filtered_items = []

# Iterate through the items and check if the fields are not empty
for item in items:
    if item['username'] and item['Win'] and item['Lose'] and item['Score']:
        filtered_items.append({'username': item['username'], 'Win': item['Win'], 'Lose': item['Lose'], 'Score': item['Score']})
        
# Return the filtered items
return filtered_items

Can anyone shed some light on this please?

Thank you :-)

ND Bhav
質問済み 1年前661ビュー
1回答
2

You should first check the items have those keys before using them:

for item in items:
    if all(key in item for key in ("username", "Win", "Lose", "Score")):
       if item['username'] and item['Win'] and item['Lose'] and item['Score']:
profile pictureAWS
エキスパート
回答済み 1年前
  • Thank you for replying :-)

    Ended up doing it another way:

    import boto3

    dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('INSERT DATABASE NAME HERE')

    def lambda_handler(event, context): users = table.scan()['Items'] filtered_users = [] for user in users: if user.get('Win') or user.get('Lose') or user.get('Score'): filtered_users.append({ 'username': user.get('username'), 'Win': user.get('Win'), 'Lose': user.get('Lose'), 'Score': user.get('Score') }) return filtered_users

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ