Skip to content

Instantly share code, notes, and snippets.

View Valdes-Tresanco-MS's full-sized avatar

Mario Sergio Valdés Tresanco Valdes-Tresanco-MS

  • University of Medellín
  • Colombia
View GitHub Profile
@Valdes-Tresanco-MS
Valdes-Tresanco-MS / multiindex_to_nested_dict.py
Created September 5, 2021 08:57
Converts a pandas Multiindex to a nested dict
import pandas as pd
from types import Union # in Python 3.10 in not needed since we can define the Union as "type | type"
def multiindex2dict(p: Union[pd.MultiIndex, dict]) -> dict:
"""
Converts a pandas Multiindex to a nested dict
:parm p: As this is a recursive function, initially p is a pd.MultiIndex, but after the first iteration it takes
the internal_dict value, so it becomes to a dictionary
"""