Converting CSV to DICT(PP)

Screen Link:

My Code:

from csv import reader
open_file = open('users.csv')
read_file = reader(open_file)
data = list(read_file)
data = data[1:]

name_to_email = {data[name] : data[email] for data in range(len(name))}
william_email = name_to_email["William Chase"]
madison_email = name_to_email["Madison Wallace"]

What I expected to happen: I undserstand I did something wrong here, can anyone explain what is missing or i did wrong and how to debug this?
Also in the answer given i am not able to understand why file.close() is used.
Thanks a lot for your help :slight_smile:

What actually happened:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-b1c47bd067dc> in <module>
      5 data = data[1:]
      6 
----> 7 name_to_email = {data[name] : data[email] for data in range(len(name))}
      8 william_email = name_to_email["William Chase"]
      9 madison_email = name_to_email["Madison Wallace"]

<ipython-input-1-b1c47bd067dc> in <dictcomp>(.0)
      5 data = data[1:]
      6 
----> 7 name_to_email = {data[name] : data[email] for data in range(len(name))}
      8 william_email = name_to_email["William Chase"]
      9 madison_email = name_to_email["Madison Wallace"]

TypeError: 'int' object is not subscriptable
1 Like

Hi @uditchauhan,

The issue is in the line where you use the dictionary comprehension. You haven’t defined in advance what name and email are. They are row[0] and row[1] of each row in your data correspondingly. Hence you can re-write this line in the following way:

name_to_email = {row[0]: row[1]  for row in data}

About file.close(). Here it’s not crucial, but it’s a good practice to always close a file after using. Because sometimes, for example if you made some changes to the file, they are not shown until you close the file.

2 Likes

Youre a lifesaver, thanks again for the quick help. I will write this, i wasnt sure where to define but now i got it :slight_smile:

ok understood so the position of file.close() should be the same as it is in this solution right, or we have to write it in the end of code?

1 Like

Yes, you can close the file as soon as you used it (i.e. opened it, read it and rendered it as a list of lists). Exactly as it happens in the line 5 of the solution.

1 Like

Great, thank you so much. Have a nice day/night :slight_smile:

You are welcome @uditchauhan :blush: Have a nice day you too!

1 Like