Home > Net >  Flat a list of containing only one dict
Flat a list of containing only one dict

Time:12-15

I have a dict which contain a list product which will contain only one dict:

d = {
    "thickness": 90.0,
    "mass_surf": 37.8,
    "res_therm": 0.75,
    "codename": "codename1",
    "category": "category1",
    "sub_categories": [
        "sub_categories1"
    ],
    "secondary_targets": [
        "secondary_targets1",
        "secondary_targets2",
        "secondary_targets3"
    ],
    "product": [
        {
            "codename": "codename1",
            "purpose": "purpose1",
            "category": "category1",
            "material": "material1"
        }
    ]
}

I want to flat the product list of dict to obtain this:

d = {
    "thickness": 90.0,
    "mass_surf": 37.8,
    "res_therm": 0.75,
    "codename": "codename1",
    "category": "category1",
    "sub_categories": [
        "sub_categories1"
    ],
    "secondary_targets": [
        "secondary_targets1",
        "secondary_targets2",
        "secondary_targets3"
    ],
    "product.codename": "codename1",
    "product.purpose": "purpose 1",
    "product.purpose": "purpose1",
    "product.category": "category1",
    "product.material": "material1"
}

How can I do this?

product list will always contains only one item

CodePudding user response:

You can flatten the internal dict and update it back to the original dict. Eg.,

product = d.pop("product")[0]
flattened = {f"product.{key}": value for key, value in product.items()}
d.update(flattened)

This should do the trick.

  • Related