簡體   English   中英

無效類型參數 class str,有效類型 class dict

[英]Invalid type parameter class str, valid types class dict

所以我正在嘗試使用 put_item 同步 Dynamodb 表。 但是我遇到了一個問題。

Invalid type for parameter Item.Artist, value: No One You Know, type: <class 'str'>, valid types: <class 'dict'>

通過閱讀使用 put_item 時的文檔,它需要一個字典,所以基本上是這樣的:

'{'Artist': {'S': 'No One You Know'},'SongTitle': {'S': 'Call Me Today'}}'

為了正確添加它。

這是我的代碼:

#!/usr/bin/python3
import boto3
source = boto3.resource('dynamodb', 'us-east-1')
dest = boto3.client('dynamodb', 'us-west-2')

def sync(source, dest):
     table = source.Table("myMusic")
     scan_kwargs = {
         'ProjectionExpression': "Artist, SongTitle"
     }
     done = False
     start_key = None
     while not done:
         if start_key:
             scan_kwargs['ExclusiveStartKey'] = start_key
         response = table.scan(**scan_kwargs)
         for item in response['Items']:
             dest.put_item(TableName="myMusic", Item=item)
             #print(item)
         start_key = response.get('LastEvaluatedKey', None)
         done = start_key is None


sync(source, dest)

因此,如果我取消注釋打印語句,我會得到:

{'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'}

有什么方法可以對 output 進行消毒或添加額外的必需的“S”,或者我是不是走錯了路?

在您的代碼中的某個階段,您將在取消注釋打印語句時打印您所說item = {'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'}

使用以下代碼片段:

newItem = { 'Artist': {}, 'SongTitle': {} }

newItem['Artist']['S'] = item['Artist']
newItem['SongTitle']['S'] = item['SongTitle']

所以整個代碼變成:

#!/usr/bin/python3
import boto3
source = boto3.resource('dynamodb', 'us-east-1')
dest = boto3.client('dynamodb', 'us-west-2')

def sync(source, dest):
     table = source.Table("myMusic")
     scan_kwargs = {
         'ProjectionExpression': "Artist, SongTitle"
     }
     done = False
     start_key = None
     while not done:
         if start_key:
             scan_kwargs['ExclusiveStartKey'] = start_key
         response = table.scan(**scan_kwargs)
         for item in response['Items']:
             
#######################  SNIPPET  #######################  
             newItem = { 'Artist': {}, 'SongTitle': {} }

             newItem['Artist']['S'] = item['Artist']
             newItem['SongTitle']['S'] = item['SongTitle']
#######################  SNIPPET  #######################  

             dest.put_item(TableName="myMusic", Item=newItem)
             #print(item)
         start_key = response.get('LastEvaluatedKey', None)
         done = start_key is None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM