简体   繁体   中英

Convert one dictionary to list of dictionaries

I need to convert one dictionary, whose values are in a list to a list of dictionaries.

For example, the following dictionary:

only_dict = {'First': [1, 2], 'Second': [3, 4]}

Should have the following output, where values are no longer in a list.

out_lst = [{'First': 1, 'Second': 3}, {'First': 2, 'Second': 4}]
[{"First": v[0], "Second": v[1]} for v in only_dict.values()]

Here is a generic version for lists of any length:

only_dict = {'First': [1,2,3], 'Second': [4,5,6], 'Third': [7,8,9]}
[dict(zip(only_dict, val)) for val in only_dict.values()]

output:

[{'First': 1, 'Second': 2, 'Third': 3},
 {'First': 4, 'Second': 5, 'Third': 6},
 {'First': 7, 'Second': 8, 'Third': 9}]

A simple version for any length of the lists. First, get the maximum list length:

count = max(*[len(x) for x in only_dict])

Construct each of the dictionaries one by one:

out_lst = [{k: v[i] for k, v in only_dict.items() if len(v) >= i} for i in range(count)]

A simple approach to fill the list based on the total length of initial dictionary.

only_dict = {'First': [1, 2], 'Second': [3, 4]}
out_dict = {index: {} for index in range(len(only_dict.keys()))}
def fill(key, values):
    for index, val in enumerate(values):
        out_dict[index][key] = val
[fill(key, val) for key, val in only_dict.items()]
out_dict = list(out_dict.values())

print(out_dict)

Prints the output

[{'First': 1, 'Second': 3}, {'First': 2, 'Second': 4}]

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