python - 在 python 中打印具有格式的混合类型字典

标签 python string printing dictionary format

我有

d = {'a':'Ali', 'b':2341, 'c':0.2424242421, 'p':3.141592}

我想将它打印到 std 但我想格式化数字,比如删除过多的小数位,比如

{'a':'Ali', 'b':2341, 'c':0.24, 'p':3.14}

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

但是,当__str__() ing 或以某种方式输出要打印的字符串时,是否有更好的方法来格式化 字典中的所有数字?

编辑:
我正在寻找像这样的魔法:

'{format only floats and ignore the rest}'.format(d)

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

最佳答案

您可以使用 round 将 float 四舍五入到给定的精度。要识别 float ,请使用 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}

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.

更新:

您可以创建 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}

关于python - 在 python 中打印具有格式的混合类型字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489353/

相关文章:

html - 打印模式下 twitter bootstrap 表中的某些行宽度错误且无边框

c - 反向打印字符串值

python - Sieve of Eratosthenes set-实现困惑

python - 无法在python中导入模块

python - 使用 beautifulsoup,如何在 html 页面中引用表行

c++ - 如何使用 L(或不使用)在变量中传递 unicode 字符串

ruby - 如何搜索、递增和替换 Ruby 字符串中的整数子字符串?

linux - AWK 字符串按字母顺序比较

python - 是否有一个Python包可以解析带有节的可读数据文件

javascript - 通过 JavaScript 打印网页的子集