简体   繁体   中英

How to format all the values in dictionary using python?

how can we format a number in a dictionary in python? I have {'num1': 0.111, 'num2': 0.222} How to round them up or make them like 0.1 and 0.2 in the printed results?

As @j1-lee said in comment, you don't "format a number variable", but instead you format the printed value.

To print the key-value pairs:

d = {'num1' : 0.111, 'num2' : 0.222}
for k, v in d.items():
    print(f"{k}: {v:.2f}")

More Explanation
You can update the values in the dict to round the floats, but that would be a terrific idea and you would encounter rounding issues all of the time.

If you insist doing so though,

d = {'num1' : 0.111, 'num2' : 0.222}
for k, v in d.items():
    d[k] = round(v,2)
print(d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM