AWS BotoCore 错误 - AttributeValue 不能包含空字符串

dan*_*oll 4 python dictionary amazon-s3 boto amazon-dynamodb

我正在尝试使用由 PostgreSQL 数据库构成的旧事件存储中的数据填充 DynamoDB 数据库。在它运行了很大一部分 db 条目后,尝试调用该put_item函数时会抛出此错误。

botocore.exceptions.ClientError:-

调用 PutItem 操作时发生错误 (ValidationException):一个或多个参数值无效:一个 AttributeValue 可能不包含空字符串

我决定重新运行代码并通过在插入之前转储所有表属性来查看发生了什么。

我可以看到唯一的“空字符串”在answer_string字典的属性中,称为details,见下文:-

Importing event type 5 completed by user: 1933
1933 5 {'answer': {'difficulty': 1, 'answer_string': ''}, 'card_id': n 
'13448', 'review_id': '153339', 'time_spent': 2431}
62 153339
2017-01-18 00:46:48.373009+00:00 2017-01-18 00:46:48.364217+00:00
Run Code Online (Sandbox Code Playgroud)

我很确定这就是导致抛出错误的原因,因为其他表属性都不正确。

我的问题是details字典可以来自几十个不同的位置,每个details字典可以有不同的属性 - 具有answer_string属性的只是许多可能的字典配置之一。我不可能检查字典的所有可能配置并验证它们都没有空字符串。

有没有一种方法可以对字典进行一次全面检查,看看它的任何部分是否为空?

vla*_*ror 5

或者,如果您想用None值替换所有空字符串:

def removeEmptyString(dic):
    for e in dic:
        if isinstance(dic[e], dict):
            dic[e] = removeEmptyString(dic[e])
        if (isinstance(dic[e], str) and dic[e] == ""):
            dic[e] = None
        if isinstance(dic[e], list):
            for entry in dic[e]:
                removeEmptyString(entry)
    return dic

dictionaryWithEmptyStringsReplacedWithNone = removeEmptyString(dicrionaryWithEmptyStrings)
Run Code Online (Sandbox Code Playgroud)

它远非完美,但它有效。


Dun*_*dan 4

如果您想获取仅包含所有具有空值的键的字典,您可以简单地将字典理解应用于details-dict 来获取所有具有空值的键值对。例如:

empty_values = {key: value for key, value in details.items() if not value}
Run Code Online (Sandbox Code Playgroud)

如果您想过滤掉具有空值的键值对,那么您将得到一个所有键都有值的字典,只需使用相同的理解而无需not

details = {key: value for key, value in details.items() if value}
Run Code Online (Sandbox Code Playgroud)