以python格式打印混合类型词典



我有

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

我想把它打印成std,但我想格式化数字,比如去掉多余的小数位数,比如

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

很明显,我可以浏览所有的项目,看看它们是否是一种"类型",我想格式化它们并打印结果,

但是,有没有更好的方法在__str__()format字典中的所有数字,或者以某种方式将字符串打印出来?

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

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

或者来自CCD_ 3世界或类似的东西。

您可以使用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}

关于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}

要将浮点转换为两位小数,请执行以下操作:

a = 3.141592
b = float("%.2f" % a) #b will have 2 decimal places!
您还可以执行以下操作:
b = round(a,2)

因此,美化你的字典:

newdict = {}
for x in d:
    if isinstance(d[x],float):
        newdict[x] = round(d[x],2)
    else:
        newdict[x] = d[x]

你也可以做:

newdict = {}
for x in d:
    if isinstance(d[x],float):
        newdict[x] = float("%.2f" % d[x])
    else:
        newdict[x] = d[x]

尽管第一个是推荐的!

最新更新