gpt4 book ai didi

python-3.x - 无效类型参数类 str,有效类型类 dict

转载 作者:行者123 更新时间:2023-12-02 02:15:05 25 4
gpt4 key购买 nike

所以我尝试使用 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'}

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

最佳答案

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

使用以下代码片段:

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

关于python-3.x - 无效类型参数类 str,有效类型类 dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67287259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com