Python Nested Convert Dict Value

Aug 1, 2019

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

from decimal import Decimaldef 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 pprintimport decimalfrom decimal import Decimaldata = {    '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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.