Home > Enterprise >  Convert the data type of the value of the dictionary from floating point to percentage with two deci
Convert the data type of the value of the dictionary from floating point to percentage with two deci

Time:11-02

Suppose I have a dictionary d, the data type of the value is float, since this value is the accuracy rate. So I want to convert it to a percentage:

d = {'import': 0.5833333333333334, 'export': 0.4166666666666667}
d.values()
d.items()
for k, v in d.items():
     d[v] = d[format(v,'.2%')]

The ultimate goal is to remove the quotation marks and curly braces on the key, and convert it into a string to pass in the title of a matplotlib plot:

plt.title(f"Models accuracy is :\n{str(d)}")

The title of the figure will become like this:

Models accuracy is :
import: 58.33%, export: 41.67%

How to achieve this?

CodePudding user response:

Something like:

# format each metric
# this will give you 2 decimal places
results = [f"{key}:{100*d[key]:.2f}%" for key in d]

# combine into a single string
results_combined = ", ".join(results)

# set as title
title = f"Models accuracy is :\n{results_combined}"
  • Related