How to format floats in a nested dictionary?
Author: pinikopCreated Feb 21, 2023Updated Aug 31, 2026
I have a nested dict and some of the (nested) values are floating numbers. how can I integrate a custom formatter that can specify the number of significant digits?
perhaps it would be a good idea to add an option of float formating?
def custom_formatter(x):
# Check if x is a float and format it to 2 significant digits
if isinstance(x, float):
return f'{x:.2f}'
# Recursively apply the formatter to nested dictionaries and lists
elif isinstance(x, dict):
return {k: custom_formatter(v) for k, v in x.items()}
elif isinstance(x, list):
return [custom_formatter(v) for v in x]
else:
return xinput:
my_dict = {
"value1": 1.234567,
"value2": {
"value3": 2.345678,
"value4": [3.456789, 4.567890],
},
"value5": [
5.678901,
{"value6": 6.789012}
]
}
desire output: ic(my_dict)
ic| my_dict: {'value1': 1.23,
'value2': {'value3': 2.34, 'value4': [3.45, 4.56]},
'value5': [5.67, {'value6': 6.78}]}Source: gruns/icecream