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}]
CodePudding user response:
[{"First": v[0], "Second": v[1]} for v in only_dict.values()]
CodePudding user response:
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)]
CodePudding user response:
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}]
CodePudding user response:
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}]