You can use round to round the float with a given precision. To define floats, use 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 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 subclass dict and override __str__ behavior:
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}
source share