![](/img/trans.png)
[英]How to get all the values of xml elements into a single dictionary using python?
[英]How to format all the values in dictionary using python?
我们如何在 python 的字典中格式化数字? 我有 {'num1': 0.111, 'num2': 0.222} 如何在打印结果中将它们四舍五入或使它们像 0.1 和 0.2?
正如@j1-lee 在评论中所说,您不会“格式化数字变量”,而是格式化打印的值。
要打印键值对:
d = {'num1' : 0.111, 'num2' : 0.222}
for k, v in d.items():
print(f"{k}: {v:.2f}")
更多解释
您可以更新 dict 中的值以舍入浮点数,但这将是一个绝妙的主意,您会一直遇到舍入问题。
如果你坚持这样做,
d = {'num1' : 0.111, 'num2' : 0.222}
for k, v in d.items():
d[k] = round(v,2)
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.