Home > Blockchain >  How to convert single dictonary with list as key values into list of dictonaries?
How to convert single dictonary with list as key values into list of dictonaries?

Time:11-01

my_dict = {'index':[1,2,3], 'answer':['A','D','B']}

I want to convert this my_dict into this below list

[{'index': 1,'answer': 'A'}, {'index':2, 'answer': 'D'}, {'index': 3, 'answer': 'B'}]

I have the solution but it depends upon pandas library, but I am looking for a way to do it without any dependencies

pandas solution:

import pandas as pd
output = list(pd.DataFrame(my_dict).T.to_dict().values())
output

[{'index': 1, 'answer': 'A'},
 {'index': 2, 'answer': 'D'},
 {'index': 3, 'answer': 'B'}]

CodePudding user response:

I'd prefer:

[{'index': x, 'answer': y} for x, y in zip(*my_dict.values())]

Or if you care about order:

[{k: ip[i] for i, k in enumerate(my_dict)} for ip in zip(*my_dict.values())]

Output:

[{'index': 1, 'answer': 'A'}, {'index': 2, 'answer': 'D'}, {'index': 3, 'answer': 'B'}]

Or as @Jab mentioned, you could use:

[dict(zip(my_dict, ip)) for ip in zip(*my_dict.values())]

Direct zipping.

CodePudding user response:

This should do it for this example. Let me know if you wanted something more general.

[
  {'index': index, 'answer': answer}
  for index, answer in zip(my_dict['index'], my_dict['answer'])
]
  • Related