简体   繁体   中英

dictionary of list to list of dictionaries

I was wondering what the best method is to make a function convert(dict_of_list) that converts a list of dictionaries to the following:

Before conversion, it is represented as: {'A': ['A1', 'A2'], 'B': ['B1', 'B2']}

After conversion, it is represented as: [{'A': 'A1', 'B': 'B1'}, {'A': 'A2', 'B': 'B2'}]

I have the following answer, but it feels like it could be done much easier

def convert(dict_of_lists):
    if len(dict_of_lists) == 0:
        return []

    keys = dict_of_lists.keys()
    nr_entries = None
    for k in keys:
        if nr_entries == None:
            nr_entries = len(dict_of_lists[k])
        if len(dict_of_lists[k]) != nr_entries:
            return None

    result = []
    for i in range(nr_entries):
        entry = dict()
        for k in keys:
            entry[k] = dict_of_lists[k][i]
        result.append(entry)
    return result

You can use zip :

d = {'A': ['A1', 'A2'], 'B': ['B1', 'B2']}
r = [dict(i) for i in zip(*[[(a, i) for i in b] for a, b in d.items()])]

Output:

[{'A': 'A1', 'B': 'B1'}, {'A': 'A2', 'B': 'B2'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM