Reputation:
I have a csv file that looks like the following:
I need to convert this into a list of dictionaries that looks like the following:
users = [{ "id": 0, "name": "James" },
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jake" },
{ "id": 3, "name": "Jim" },
{ "id": 4, "name": "Alex" },
{ "id": 5, "name": "Adam" },
{ "id": 6, "name": "Ryan" },
{ "id": 7, "name": "Katie" },
{ "id": 8, "name": "Julia" },
{ "id": 9, "name": "Sam" }]
I also have this CSV file of "connections" between each user based on their ids:
I have been trying for hours to get this to just be a simple list of tuples that look like the following:
friends = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]
I have tried every way of importing csv files I know, but I've never dealt with one that wants me to make a new dictionary for every entry, and i dont think ive ever dealt with one without headers like this. While I wish I could just add headers and my my life easier, it must look like the example I gave above for the rest of my code to work. Please let me know if you have any idea how to do this. Thank you!
I completed this entire project of mine, but had to hardcode the mentioned dictionary and list because I simply do not know how to handle having no headers in a CSV and making them look like this. Any help would be greatly appreciated!
Upvotes: 1
Views: 4294
Reputation: 1603
As far as I understand this should solve your first problem. You should be able to easily modify this code to suit your second use case.
users = []
with open('<your_file_name.csv>', 'r') as f: ##open the file in read mode
for l in f.readlines(): ## get all the lines
row_id, row_name = l.strip('\n').split(',') ## unpack the values (assumes only two columns)
users.append({'id':row_id, 'name' : row_name}) ## add to your list
As mentioned by darksky, using the csv module is probably better in terms of code stability so take a look at his answer too
Upvotes: 0
Reputation: 2100
Let's look at using the standard python csv
module for parsing your files.
import csv
with open('names.csv') as csvfile:
# create a list to store results
users = []
# read the file
reader = csv.reader(csvfile)
# for every line in the csv
for row in reader:
#create a user dict
user = {}
# fill in the user.
user["name"] = row[1]
user["id"] = row[0]
# add this user to the list of users
users.append(user)
Similarly for friends,
import csv
with open('friends.csv') as csvfile:
# create a list to store results
friends = []
# read the file
reader = csv.reader(csvfile)
# for every line in the csv
for row in reader:
#create a friend tuple
friend = (row[0], row[1])
# add this friend to the list of friends
friends.append(friend)
Upvotes: 1