I have a dictionary that contains a list:
d = {'A': [1, 2, 3], 'B': 'hello'}
I want to unpack it in a list of dictionaries like this:
l = [{'A': 1, 'B': 'hello'},
{'A': 2, 'B': 'hello'},
{'A': 3, 'B': 'hello'}]
I tried with the following function:
def unpack_dict(dict_to_unpack):
unpacked_dicts = []
for key in dict_to_unpack:
if type(dict_to_unpack[key]) is list:
for value in dict_to_unpack[key]:
temp_dict = dict_to_unpack
temp_dict[key] = value
unpacked_dicts.append(temp_dict)
return unpacked_dicts if unpacked_dicts else dict_to_unpack
But I get this as a result instead:
[{'A': 3, 'B': 'hello'},
{'A': 3, 'B': 'hello'},
{'A': 3, 'B': 'hello'}]
Thanks for the answers.