Reputation: 47
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. How do I convert it into a dict as shown in the example?
Upvotes: 1
Views: 89
Reputation: 67
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.
Upvotes: 0
Reputation: 5223
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?'}]
Upvotes: 1