blackraven
blackraven

Reputation: 5597

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

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': 'value2', 'key3': 'value3'},
    {'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
    {'key1': 'value7', 'key2': 'value8', 'key3': 'value9'}
]

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?

Upvotes: 1

Views: 95

Answers (2)

RJ Adriaansen
RJ Adriaansen

Reputation: 9619

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'}]

Upvotes: 2

MiH
MiH

Reputation: 352

[ 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?

Upvotes: 2

Related Questions