Printing 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 to std, but I want to format numbers, for example, remove extra decimal places, something like

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

Obviously, I can go through all the elements and see if they are the โ€œtypeโ€ that I want to format and format, and print the results,

But is there a better way to format all the numbers in a dictionary with __str__() ing or somehow get a string to print?

EDIT:
I am looking for magic like:

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

or something from the world of yaml or similar.

+4
source share
2 answers

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} 
+4
source

To convert a float to two decimal places, do the following:

a = 3.141592
b = float("%.2f" % a) #b will have 2 decimal places!
you also can:
b = round(a,2)

So, to decorate your dictionary:

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

You can also do:

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

although the first is recommended!

0
source

Source: https://habr.com/ru/post/1489900/


All Articles