input
list=[['What did the Vedas contain large collections of?'], ['What did the Vedas contain large collections of?'], `['What was accompanied by the rise of ascetic movements in Greater Magadha?'], ['In what part of India did Wootz steel originate?'], ['What country was ruled by dynasties during the Classical period?']]`
output
dict=[{"question":"What did the Vedas contain large collections of?"},{"question":"What did the Vedas contain large collections of?"},{"question":"What was accompanied by the rise of ascetic movements in Greater Magadha?"}]
I have a 2D list. then how to convert it into a dict as shown in example?
CodePudding user response:
Just traverse the list, create a dictionary for each element and append them to the new variable d
:
l=[['What did the Vedas contain large collections of?'], ['What did the Vedas contain large collections of?'], ['What was accompanied by the rise of ascetic movements in Greater Magadha?'], ['In what part of India did Wootz steel originate?'], ['What country was ruled by dynasties during the Classical period?']]
d = []
for i in l:
d.append({"question":i[0]})
print(d)
Output:
[{'question': 'What did the Vedas contain large collections of?'}, {'question': 'What did the Vedas contain large collections of?'}, {'question': 'What was accompanied by the rise of ascetic movements in Greater Magadha?'}, {'question': 'In what part of India did Wootz steel originate?'}, {'question': 'What country was ruled by dynasties during the Classical period?'}]
CodePudding user response:
res = [{'question': x[0]} for x in list]
CodePudding user response:
In Your example in output You have list again. But in any case you can use this code:
mydict = [{"question":e[0]} for e in mylist]
PS I'm renamed your vars named list
, dict
to mylist
, mydict
because it's not so good practice to use class names from standard lib for local vars.