将Decimal(str(value))传递给字典以获取原始值 [英] Passing a Decimal(str(value)) to a dictionary for raw value
问题描述
我需要将值作为类'decimal.Decimal'传递给字典,并且不断发生以下情况:
I'm needing to pass values to a dictionary as class 'decimal.Decimal', and the following keeps happening:
from decimal import *
transaction_amount = 100.03
transaction_amount = Decimal(str(transaction_amount))
item = {
'transaction_amount': transaction_amount
}
print(item)
结果:
{'transaction_amount': Decimal('100.03')}
如何获得原始的100.03结果,而不是Decimal('100.03')?
How do I attain the raw 100.03 result, rather than Decimal('100.03')?
这是我要保存的词典:
{'transaction_amount': 100.03)}
当我这样做时:
print(transaction_amount)
结果符合预期:
100.03
那么我要去哪里错了?
So where am I going wrong?
我认为这个问题应该被否决.
I don't see any reason why this question should be downvoted.
推荐答案
当您要求python打印对象时,它将打印该对象的文本表示形式.
When you ask python to print an object, it'll print the textual representation of that object.
这里的可变项是字典,因此其表示形式如下:
Here your variable item is a dictionnary, so its representation is as follow:
{ key: value [, repeat]}
如果要在字典中输入值,则必须按如下所示进入指定的键:
If you want the value inside your dictionnary, you would have to go at the specified key like so :
print(item[transaction_amount])
因此,基本上,您的代码很好,也使用了十进制,但是您并不是在测试它的好方法. ;)发生了很多.
So basically, your code was fine and your use of decimal too, but you weren't testing it the good way. ;) Happens a lot.
修改:
值得注意的是,由于在字典对象中得到的是Decimal(100.03)
,即使像我之前显示的那样打印键-值对的值,也不会得到纯100.03,但可能会得到Decimal(100.03)
.
It's worth noting that, since what you are getting within the dictionnary object is Decimal(100.03)
, even when printing the value of the key-value pair as I showed previously, you won't get a pure 100.03, but probably Decimal(100.03)
.
我将搜索有关如何获取字符串的一些文档. Welp显然不,它应该像一种魅力.
I'll search some documentation as to how to get the string. Welp apparently no, it should work like a charm.
我没有正确地回答问题(此后已对其进行编辑).
但是,由于注释部分中的对话很长时间,因此将保留在此处.
I didn't get the question (which has been edited since then) right.
However because of the extended conversation in the comment section, it'll remain here.
这篇关于将Decimal(str(value))传递给字典以获取原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!