使用python打印格式的混合类型字典

Ali*_*Ali 5 python printing string format dictionary

我有

d = {'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592}
Run Code Online (Sandbox Code Playgroud)

我想将其打印到std,但我想格式化数字,例如删除多余的小数位,例如

{'a':'Ali', 'b':2341, 'c':0.24, 'p':3.14}
Run Code Online (Sandbox Code Playgroud)

显然,我可以遍历所有项目,看看它们是否是“类型”,我想对其进行格式化和格式化并打印结果,

但是,format__str__()ing或以某种方式打印出字符串时,是否有更好的方法来处理字典中的所有数字?

编辑:
我正在寻找一些魔术,如:

'{format only floats and ignore the rest}'.format(d)
Run Code Online (Sandbox Code Playgroud)

或来自yaml世界或类似国家的东西。

Ash*_*ary 5

您可以使用round将浮点数四舍五入到给定的精度。要识别浮点数,请使用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}
Run Code Online (Sandbox Code Playgroud)

帮助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.
Run Code Online (Sandbox Code Playgroud)

更新:

您可以创建一个子类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}
Run Code Online (Sandbox Code Playgroud)