Home > Net >  To convert a dict (with list of keys and values) into list of dict
To convert a dict (with list of keys and values) into list of dict

Time:10-24

I have a dict with a list of keys, and the values are stored separate in a list of lists:

obj = {
    'keys': ['key1', 'key2', 'key3'], 
    'items': [['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9']]
}

The desired output is to 'merge' them into a list of dict like this:

[
    {'key1': 'value1', 'key2': 'val2', 'key3': 'val3'}, 
    {'key1': 'value4', 'key2': 'val5', 'key3': 'val6'}, 
    {'key1': 'value7', 'key2': 'val8', 'key3': 'val9'}
]

I have tried this direct approach

result = []
for item in obj['items']:
        result.append(dict(zip(obj['keys'], item)))

and also shortened it to this

[dict(zip(obj['keys'], item)) for item in obj['items']]

Are there other alternatives to achieve the desired output?

And may I know what is the name of this 'merge' manipulation?

CodePudding user response:

[ dict(zip(obj['keys'], item)) for item in obj['items'] ]

Your final line has a combination of these components:

  • list comprehension, ie, [ function(x) for x in list_x ]

  • zipping of 2 lists, ie, zip(list1, list2)

Perhaps these are the names of the 'merge' manipulation you are looking for?

CodePudding user response:

You can use pandas:

import pandas as pd

obj = {
    'keys': ['key1', 'key2', 'key3'], 
    'items': [['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9']]
}

df = pd.DataFrame(obj['items'], columns=obj['keys'])
df.to_dict(orient='records')

result:

[{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
 {'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
 {'key1': 'value7', 'key2': 'value8', 'key3': 'value9'}]
  • Related