i am new to the concept of dictionaries in python.
I have a csv file with multiple columns and i want to create a dictionary such that keys are taken from 1st column and values from the second and a key:value pair is made for all rows of those two columns.
The code is as follows:
if __name__=="__main__":
reader = csv.reader(open("file.csv", "rb"))
for rows in reader:
k = rows[0]
v = rows[1]
mydict = {k:v}
print (mydict)
problem: The output returned is only for “last” or “bottom most” row of the first two columns i.e. {‘12654′:’18790’}. i want the dictionary to contain all 100 rows of the first two columns in this format. How to do that? can i run some loop on the row numbers for the first two columns to do that…i dont know how.
Here:
You were making new dictionary in every iteration, and the previous data has been lost.
Update:
You can make something like this:
This way, each value of the same key will be stored
Your code will be:
Update2: You mean?
Update3:
This should work: