I use csv.DictWriter to output csv files from a set of dictionaries. I am using the following function:
def dictlist2file(dictrows, filename, fieldnames, delimiter='\t', lineterminator='\n'): out_f = open(filename, 'w')
where dictrows is a list of dictionaries, and field names are headers that should be serialized to a file.
Some of the values ββin my list of dictionaries (dirows) are numeric - for example. float, and I would like to indicate their formatting. For example, I would like the floats to be serialized with "% .2f" rather than full precision. Ideally, I would like to point out some kind of mapping that says how to format each type, for example.
{float: "%.2f"}
which says if you see a float, format it with% .2f. Is there an easy way to do this? I don't want a subclass of DictWriter or anything complicated like this - this seems like very general functionality.
How can I do that?
The only other solution I can think of is: instead of messing with DictWriter formatting, just use the decimal package to specify the decimal precision of the float as% .2, which will result in serialization as such. Not sure if this is the best solution?
Many thanks for your help.
source share