0

I have nested list which looks something like this

my_list = [[1,'raj','CSE'],[2,'kumar','MECH'],[3,'Nisha','ECE']]

Since I need to export this in CSV I want to convert this into a dictionary. My output should be like this.

my_dict = {'id':[1,2,3],'Name':['raj','kumar','Nisha'],'Course':['CSE','MECH','ECE']}

How can I achieve this???

4
  • 1
    What have you tried already to achieve this. Also, are you required to create the expected structure? Because it seems a bit odd to have a dictionary structured that way based on the data. Commented Jul 10, 2017 at 13:05
  • Where are you getting the names from? Commented Jul 10, 2017 at 13:05
  • You should attempt this problem yourself! I'd suggest a for loop that checks the 1st, 2nd, and 3rd element in each of the nested lists, then assigns them to the proper key in a dictionary you create. Commented Jul 10, 2017 at 13:06
  • This is just an example. In the real case, I retrieve data by scraping The Web. There I can only get data in List format Commented Jul 10, 2017 at 13:13

5 Answers 5

13

Easily done with zip:

l = [[1,'raj','CSE'],[2,'kumar','MECH'],[3,'Nisha','ECE']]
d = dict(zip(['Id', 'Name', 'Course'], map(list, (zip(*l))))) 
d    
# {'Course': ['CSE', 'MECH', 'ECE'],
#  'Id': [1, 2, 3],
#  'Name': ['raj', 'kumar', 'Nisha']}

Since you want to convert it to a dict first before saving it to a csv, I'm assuming you use pandas (otherwise it'd have been easier to save it in its existing form). This is easily done:

df = pd.DataFrame(d)  # `d` is from the code snippet above.

df

  Course  Id   Name
0    CSE   1    raj
1   MECH   2  kumar
2    ECE   3  Nisha

df.to_csv('test.csv')

Alternatively, if you don't want to use pandas, just do this:

l = [[1,'raj','CSE'],[2,'kumar','MECH'],[3,'Nisha','ECE']]
 with open('test.csv', 'w') as f:
     writer = csv.writer(f)
     writer.writerow(['Id', 'Name', 'Course'])
     writer.writerows(l)

In this situation, you do not require conversion to a dictionary.

Sign up to request clarification or add additional context in comments.

1 Comment

@Wondercricket Indeed it does! Thanks, I tried this on python 3 only, wasn't sure if it'd work otherwise :)
1

An alternative to @Coldspeed's very elegant solution:

headers = ['id', 'Name', 'Course']
my_list = [[1,'raj','CSE'],[2,'kumar','MECH'],[3,'Nisha','ECE']]
my_dict = {k: [x[i] for x in my_list] for i, k in enumerate(headers)}
print(my_dict)  # {'Name': ['raj', 'kumar', 'Nisha'], 'Course': ['CSE', 'MECH', 'ECE'], 'id': [1, 2, 3]}

Comments

0

If you want just to export it to csv, Pandas is quite handy:

import pandas as pd
pd.DataFrame(my_list, columns=['id','Name','Course']).to_csv("Name.csv")

1 Comment

That seems overkill to have to require an installation of pandas for something like this.
0

A simple and elegant way to me is by zip function:

my_list = [[1,'raj','CSE'],[2,'kumar','MECH'],[3,'Nisha','ECE']]
ids, names, courses = map(list, zip(*my_list))
my_dict = {'id': ids, 'Name': names, 'Course': courses}

1 Comment

i don't refresh the answers when i read the other answers. I don't delete beacause i think my solution is more readable
-1

The answer is simple:

my_dict={
         'id':[a[0] for a in my_list],
         'Name': [a[1] for a in my_list],
         'Course':[a[2] for a in my_list]
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.