[英]Printing a mixed type dictionary with format in python
I have 我有
d = {'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592}
I want to print it out to std but I want format the numbers, like remove the excessive decimal places, something like 我想将它打印到std但我想格式化数字,比如删除过多的小数位,就像
{'a':'Ali', 'b':2341, 'c':0.24, 'p':3.14}
obviously I can go through all the items and see if they are a 'type' I want to format and format them and print the results, 显然,我可以浏览所有项目,看看它们是否是“类型”我想格式化并格式化它们并打印结果,
But is there a better way to format
all the numbers in a dictionary when __str__()
ing or in someway getting a string out to print? 但有没有更好的方法来
format
字典中的所有数字__str__()
或在某种程度上获取字符串打印?
EDIT: 编辑:
I am looking for some magic like: 我正在寻找一些神奇的东西:
'{format only floats and ignore the rest}'.format(d)
or something from the yaml
world or similar. 或来自
yaml
世界或类似的东西。
You can use round
for rounding the floats to a given precision. 您可以使用
round
来将浮动四舍五入到给定的精度。 To identify floats use isinstance
: 要识别浮动,请使用
isinstance
:
>>> {k:round(v,2) if isinstance(v,float) else v for k,v in d.iteritems()}
{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}
help on round
: 帮助上
round
:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
Update: 更新:
You can create a subclass of dict
and override the behaviour of __str__
: 您可以创建
dict
的子类并覆盖__str__
的行为:
class my_dict(dict):
def __str__(self):
return str({k:round(v,2) if isinstance(v,float) else v
for k,v in self.iteritems()})
...
>>> d = my_dict({'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592})
>>> print d
{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}
>>> "{}".format(d)
"{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}"
>>> d
{'a': 'Ali', 'p': 3.141592, 'c': 0.2424242421, 'b': 2341}
To convert float to two decimal places, do this: 要将float转换为两位小数,请执行以下操作:
a = 3.141592
b = float("%.2f" % a) #b will have 2 decimal places!
you could also do: 你也可以这样做:
b = round(a,2)
So to beautify your dictionary: 所以要美化你的字典:
newdict = {}
for x in d:
if isinstance(d[x],float):
newdict[x] = round(d[x],2)
else:
newdict[x] = d[x]
you could also do: 你也可以这样做:
newdict = {}
for x in d:
if isinstance(d[x],float):
newdict[x] = float("%.2f" % d[x])
else:
newdict[x] = d[x]
though the first one is recommended! 虽然推荐第一个!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.