Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a 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 out to std but I want format the numbers, like remove the excessive decimal places, something like

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

obviously I can go through all the items and see if they are a 'type' I want to format and format them and print the results,

But is there a better way to format all the numbers in a dictionary when __str__() ing or in someway getting a string out to print?

EDIT:
I am looking for some magic like:

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

or something from the yaml world or similar.

like image 700
Ali Avatar asked Jul 05 '13 12:07

Ali


People also ask

How do you print a dictionary format in Python?

Use pprint() to Pretty Print a Dictionary in Python Within the pprint module there is a function with the same name pprint() , which is the function used to pretty-print the given string or object. First, declare an array of dictionaries. Afterward, pretty print it using the function pprint. pprint() .

Can Python dictionary have mixed data types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.

How do you use %d and %s in Python?

Both %s and %d operatorsUses decimal conversion via int() before formatting. %s can accept numeric values also and it automatically does the type conversion. In case a string is specified for %d operator a type error is returned.

How do you print a 2d dictionary in Python?

In Python, we can add dictionaries within a dictionary to create a two-dimensional dictionary. We can also print the two-dimensional dictionary using the json. dumps() method, which turns the input into a JSON string.


1 Answers

You can use round for rounding the floats to a given precision. To identify 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 on 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 create a subclass of dict and override the behaviour of __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}
like image 127
Ashwini Chaudhary Avatar answered Sep 24 '22 20:09

Ashwini Chaudhary