0
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'}]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Aditya Rajgor
  • 953
  • 8
  • 14

2 Answers2

2

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.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    Can also be done without specifying the keys using: `[dict(zip(my_dict, ip)) for ip in zip(*my_dict.values())]` – Jab Nov 01 '21 at 06:34
  • Yeah, this does the trick! What does `*` do here? I tried without it, and it didn't work. What does this expression call by? – Aditya Rajgor Nov 01 '21 at 06:41
  • @AdityaRajgor It's unpacking! Check [this](https://stackoverflow.com/questions/12236023/what-is-the-asterisk-in-replacesomething-for-python) out. – U13-Forward Nov 01 '21 at 06:42
  • 1
    Your solution would fail if the key `index` does not come before `answer` in the input dict, which is not guaranteed by the OP. @Jab's answer on the other hand would work regardless of the order of the keys since the order of values returned by the `values` method will always correspond to their respective keys yielded by the dict's key generator. – blhsing Nov 01 '21 at 06:54
  • @blhsing Yes. But the OP doesn't specify anything about that... I am answering this based on the OP's question... Anyway, added another solution... – U13-Forward Nov 01 '21 at 06:58
  • Anything not mentioned by the OP cannot be assumed. You should simply remove your solution from your answer as it is based on an inappropriate assumption. – blhsing Nov 01 '21 at 06:59
1

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'])
]
ddg
  • 1,090
  • 1
  • 6
  • 17