无效类型参数类 str,有效类型类 dict

mcg*_*osh 2 python-3.x boto3

因此,我尝试使用 put_item 同步 Dynamodb 表。但我遇到了一个问题。

Invalid type for parameter Item.Artist, value: No One You Know, type: <class 'str'>, valid types: <class 'dict'>
Run Code Online (Sandbox Code Playgroud)

从阅读文档来看,使用 put_item 时它需要一个字典,所以本质上是这样的:

'{'Artist': {'S': 'No One You Know'},'SongTitle': {'S': 'Call Me Today'}}'
Run Code Online (Sandbox Code Playgroud)

以便正确添加。

这是我的代码:

#!/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)
Run Code Online (Sandbox Code Playgroud)

因此,如果我取消注释打印语句,我会得到:

{'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以净化输出或添加额外所需的“S”,或者我是否以错误的方式处理此问题?

小智 6

在代码的某个阶段, item = {'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'} 当您取消注释打印语句时,您将打印出您所说的内容。

使用以下代码片段:

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

newItem['Artist']['S'] = item['Artist']
newItem['SongTitle']['S'] = item['SongTitle']
Run Code Online (Sandbox Code Playgroud)

所以整个代码就变成了:

#!/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

Run Code Online (Sandbox Code Playgroud)