Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python create parse a dictionary to another format

I wanted to parse a dictionary with a format. Currently this dictionary has the same user ID in separate dictionaries and I wanted to make it same user ID in one dictionary with key and values.

Below is my current dictionary:

{
    "key1": {
        "userID1": 5,
        "userID2": 1,
        "userID3": 5
    },
    "key2": {
        "userID1": 13,
        "userID2": 24,
        "userID3": 0
    },
    "key3": {
        "userID1": 14,
        "userID2": 12,
        "userID3": 3
    }
}

Expected dictionary:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
   "userID1": {
        "key1": 5,
        "key2": 13,
        "key3": 14
    },
   "userID2": {
        "key1": 1,
        "key2": 24,
        "key3": 3
    },
   .....
}

>Solution :

Here is one possible example how you can transform the dictionary:

original_dictionary = {
    "key1": {"userID1": 5, "userID2": 1, "userID3": 5},
    "key2": {"userID1": 13, "userID2": 24, "userID3": 0},
    "key3": {"userID1": 14, "userID2": 12, "userID3": 3},
}

parsed_dictionary = {}
for k, v in original_dictionary.items():
    for kk, vv in v.items():
        parsed_dictionary.setdefault(kk, {})[k] = vv

print(parsed_dictionary)

Prints:

{
    "userID1": {"key1": 5, "key2": 13, "key3": 14},
    "userID2": {"key1": 1, "key2": 24, "key3": 12},
    "userID3": {"key1": 5, "key2": 0, "key3": 3},
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading