Roshni Hirani
Roshni Hirani

Reputation: 47

How to convert list into dict using python?

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

Answers (3)

Vyacheslav
Vyacheslav

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

User
User

Reputation: 826

res = [{'question': x[0]} for x in list]

Upvotes: 0

Cardstdani
Cardstdani

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

Related Questions