Python Nested Convert Dict Value

August 1, 2019

The method will travel dict to convert all Decimal to float.

from decimal import Decimal

def traverse_dict(data):
    def to_basic(v):
        if isinstance(v, Decimal):
            return float(v)
        return v

    for k, v in data.items():
        '''
        if isinstance(v, dict):
            traverse_dict(v)
        elif isinstance(v, list):
            data[k] = [to_basic(x) for x in v]
        else:
            data[k] = to_basic(v)
        '''

        if isinstance(v, dict):
            traverse_dict(v)
        elif isinstance(v, (list, tuple)):
            data[k] = [traverse_dict(x) if isinstance(x, dict) else to_basic(x) for x in v]
        else:
            data[k] = to_basic(v)

    return data

Usage

import pprint
import decimal
from decimal import Decimal

data = {
    'name': 'Desmond',
    'age': 40,
    'weight': Decimal(65.5),
    'height': Decimal(186.6),
    'nested': {
        'weight': Decimal(65.5),
        'height': Decimal(186.6),
    },
    'nested_dict': [
        {'weight': Decimal(65.5), 'height': Decimal(186.6),}
    ],
    'secret_numbers': [Decimal(8.88), Decimal(9.23)]
}

pprint.pprint(traverse_dict(data))

Output

{'age': 40,
 'height': 186.6,
 'name': 'Desmond',
 'nested': {'height': 186.6, 'weight': 65.5},
 'nested_dict': [{'height': 186.6, 'weight': 65.5}],
 'secret_numbers': [8.88, 9.23],
 'weight': 65.5}

NOTE: If you are converting JSON, refer to Python Json Encode Decimal.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.