0

I have a csv file with columns id, name, address, phone. I want to read each row such that I store the data in two variables, key and data, where data contains name, address and phone. I want to do this because I want to append another column country in each row in a new csv. Can anyone help me with the code in python. I tried this but it didn't work:

dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
    key, *data = row
    dict[key] = ','.join(data)
2
  • key, *data = row only works in Python 3... Commented Oct 29, 2016 at 0:53
  • Can you provide some example input and output? Commented Oct 29, 2016 at 0:53

2 Answers 2

3

key, *data = row is Python 3 syntax. For Python 2 you can do this:

key, data = row[0], row[1:]
Sign up to request clarification or add additional context in comments.

Comments

0

You can try the code below. I have put two option one is to make a list for each row, and other is comma separated. Based on the usage you can use either one.

import csv
dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
    data = []
    print row
    key,data = row[0],row[1:]
    dict[key] = data
    # dict[key] = ','.join(data)
print dict    

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.