Home > Mobile >  Convert a dictionary structure to another
Convert a dictionary structure to another

Time:03-30

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:

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?

CodePudding user response:

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.

CodePudding user response:

You can use the builtin function zip to combine the dictionary values. Individual dictionaries can then be created by zip'ping the keys of data with the newly obtained "rows":

result = [dict(zip(data.keys(), v)) for v in zip(*data.values())]
  • Related