我有一个如下所示的 csv 文件:
我需要将其转换为如下所示的字典列表:
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" }]
我还有每个用户之间基于 ID 的“连接”的 CSV 文件:
我花了几个小时试图让它成为一个简单的元组列表,如下所示:
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)]
我已经尝试过所有我知道的导入 csv 文件的方法,但我从未处理过要我为每个条目制作一本新字典的方法,而且我认为我从未处理过没有这样的标题的方法。虽然我希望我可以只添加 header ,让我的生活更轻松,但它必须看起来像我上面给出的示例,我的其余代码才能工作。如果您知道如何执行此操作,请告诉我。谢谢!
我完成了我的整个项目,但必须对提到的字典和列表进行硬编码,因为我根本不知道如何处理 CSV 中没有标题的情况并使它们看起来像这样。任何帮助将不胜感激!
最佳答案
让我们看看如何使用标准 python csv
模块来解析文件。
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)
对于 friend 来说也是如此,
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)
关于python - 如何在Python中将CSV文件转换为字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54916061/