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

Convert a dictionary structure to another

I have a dictionary of the following form:

data = {
        "name": [
            "Robin_lodging_Dorthy",
            "Robin_lodging_Phillip"
        ],
        "color": [
            "#FF0000",
            "#FF0000"
        ],
        "data": [
            [
                33.55833333333333,
                32.887499999999996,
                33.15416666666666
            ],
            [
                51.987500000000004,
                52.07916666666667,
                51.45416666666667
            ]       
        ]
    }

I want to transform the dictionary to the following form:

{'lines': [
           {'name': 'Robin_lodging_Dorthy'},
           {'color': '#FF0000'},
           {'data': [33.55833333333333,
                     32.887499999999996,
                     33.15416666666666]},

           {'name': 'Robin_lodging_Phillip'},
           {'color': '#FF0000'},
           {'data': [51.987500000000004,
                     52.07916666666667,
                     51.4541666666666]}]}

What I have done is the following, but it is a wrong approach:

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

formatted_data = []
for key in data.keys():
    for value in data[key]:
        temp = {}
        temp[key] = value
    formatted_data.append(temp)
{'lines': formatted_data}

Any idea of how can I approach it?

>Solution :

A bit of list and dict comprehension will do the trick:

data_tf = [{k:v[i] for k, v in data.items()} for i in range(len(list(data.values())[0]))]

You need to find out into how many dictionaries you need to split your data and then you just construct new dicts in a list taking i-th element from every value for each k:v pair.

EDIT: Same thing using explicit for loops, closer to your original attempt:

data_tf = []
for i in range(len(list(data.values())[0])):
    d = {}
    for k, v in data.items():
        d[k] = v[i]
    data_tf.append(d)

This results in a a list but you can easily wrap that into a dict.

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