尝试使用python boto库插入浮点数时发生DynamoDBNumberError

Roh*_*n S 6 python floating-point boto amazon-web-services amazon-dynamodb

程式码片段:

conn = dynamo_connect()

company = Table("companydb",connection=conn)

companyrecord = {'company-slug':'www-google-com12','founding-year':1991, 'randomlist' :[1,2,3,4,5], 'randomdict' : {'a':[1,2,3],'b':'something','randomnumber':10.55} }

company.put_item(data=companyrecord)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

File "C:\Python27\lib\site-packages\boto\dynamodb2\items.py", line 329, in prepare_full
    final_data[key] = self._dynamizer.encode(value)
  File "C:\Python27\lib\site-packages\boto\dynamodb\types.py", line 279, in encode
    return {dynamodb_type: encoder(attr)}
  File "C:\Python27\lib\site-packages\boto\dynamodb\types.py", line 335, in _encode_m
    return dict([(k, self.encode(v)) for k, v in attr.items()])
  File "C:\Python27\lib\site-packages\boto\dynamodb\types.py", line 279, in encode
    return {dynamodb_type: encoder(attr)}
  File "C:\Python27\lib\site-packages\boto\dynamodb\types.py", line 305, in _encode_n
    raise DynamoDBNumberError(msg)
boto.dynamodb.exceptions.DynamoDBNumberError: BotoClientError: Inexact numeric for `10.55`
Run Code Online (Sandbox Code Playgroud)

小智 11

如果您正在处理更大的集合并且希望避免按记录处理来转换十进制,这会有所帮助。

from decimal import Decimal

import json

changed_data = json.loads(json.dumps(data), parse_float=Decimal)
Run Code Online (Sandbox Code Playgroud)


Zda*_*daR 6

是的,GitHub 上有与浮点数相关的已知问题10.5,可能有 2 种解决方法,首先,如果您愿意存储而不是10.55,那么我想它会正常工作,另一种是将浮点值存储为字符串或整数,并且稍后在访问时对其进行调制。

因此,您选择了字符串部分,然后您可以将其存储为'10.55'而不是10.55,稍后当您访问表中的值时,您可以简单地使用float("10.55"),然后就完成了。

另一种方法是将其存储为整数,首先选择一个精度值(例如2位小数值),然后将其存储10.551055(乘以100,因为2位小数精度),在访问它时,您可以简单地使用它1055/100.0,您将得到10.55

  • 这不是问题的解决方案,它只是一个小技巧。 (3认同)

kk1*_*957 5

请改用 Decimal(str(your_number))。请参阅https://github.com/boto/boto3/issues/665