Home > Mobile >  represent parent and child relation by dot(.) in python
represent parent and child relation by dot(.) in python

Time:10-26

My input is:

a = {
    "name": "a",
    "address": {
        "state": "b",
        "full": {
            "city": "c"
        }
    }
}

my expected output is:

{
    "name": "a",
    "address.state": "b",
    "address.full.city": "c"
}

I have try many time but its very difficult.

CodePudding user response:

Using Recursion

input_dict = { "name": "a", "address": { "state": "b", "full": { "city": "c" } } }
def format_dict(input_dict, parent=None, res = {}):
    for k, v in input_dict.items():
        if isinstance(v, dict):
            if parent:
                format_dict(v, f"{parent}.{k}", res)
            else:
                format_dict(v, f"{k}", res)
        else:
            if parent:
                res[f"{parent}.{k}"] = v
            else:
                res[k] = v
a = {}
format_dict(input_dict, None, a)
print(a)
# {'name': 'a', 'address.state': 'b', 'address.full.city': 'c'}

CodePudding user response:

Code:

import pandas as pd
list(pd.json_normalize(YourDict).T.to_dict().values())[0]

Output:

{'name': 'a', 'address.state': 'b', 'address.full.city': 'c'}
  • Related