Search code examples
pythonpython-3.xdictionarynestedtransformation

python nested dict reorganization to list


Do you know if there is a quick method to do the following dictionary transformation? (without looping through dict's keys and construct it from scratch)

From this nested python dictionary:

{
    "demographicAll": {
        "allAges": {
            "rating": "8.8",
            "votes": "2327099"
        },
        "agesUnder18": {
            "rating": "9.0",
            "votes": "1050"
        },
        "ages18To29": {
            "rating": "9.0",
            "votes": "363089"
        },
        "ages30To44": {
            "rating": "8.8",
            "votes": "914737"
        },
        "agesOver45": {
            "rating": "8.2",
            "votes": "182612"
        }
    }
}

to this one:

{

    "demographicAll": [
        {
            "ageRange": "allAges",
            "rating": "8.8",
            "votes": "2327099"
        },{
            "ageRange": "agesUnder18",
            "rating": "9.0",
            "votes": "1050"
        },{
            "ageRange": "ages18To29",
            "rating": "9.0",
            "votes": "363089"
        },{
            "ageRange": "ages30To44",
            "rating": "8.8",
            "votes": "914737"
        },{
            "ageRange": "agesOver45",
            "rating": "8.2",
            "votes": "182612"
        }
    ]
}

Solution

  • The best I was able to do (it still loops through the dictionary inside the list comprehension) is:

    mydict =    {
        "demographicAll": {
            "allAges": {
                "rating": "8.8",
                "votes": "2327099"
            },
            "agesUnder18": {
                "rating": "9.0",
                "votes": "1050"
            },
            "ages18To29": {
                "rating": "9.0",
                "votes": "363089"
            },
            "ages30To44": {
                "rating": "8.8",
                "votes": "914737"
            },
            "agesOver45": {
                "rating": "8.2",
                "votes": "182612"
            }
        }
    }
    
    d = mydict["demographicAll"]
    mydict["demographicAll"] = [d[key] for key in d if not d[key].update({'ageRange':key})]