如何在python中将CSV文件转换为字典列表

如何在python中将CSV文件转换为字典列表,python,csv,Python,Csv,我有一个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": "Ka

我有一个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" }]
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)]

我需要将其转换为字典列表,如下所示:

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" }]
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)]
我还拥有每个用户之间基于其ID的“连接”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" }]
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文件的方法,但是我从来没有遇到过一种需要我为每个条目制作一本新词典的方法,我想我从来没有遇到过这样没有标题的。虽然我希望我可以只添加标题,让我的生活更轻松,但它必须看起来像我上面给出的示例,以便我的其余代码工作。如果你知道怎么做,请告诉我。谢谢大家!


我完成了我的整个项目,但不得不对提到的字典和列表进行硬编码,因为我根本不知道如何处理CSV中没有标题的情况,并使它们看起来像这样。任何帮助都将不胜感激

据我所知,这将解决您的第一个问题。您应该能够轻松地修改此代码以适合您的第二个用例

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
users=[]
将open(“”,'r')作为f:##以读取模式打开文件
对于f.readlines()中的l:##获取所有行
行_id,行_name=l.strip('\n').split(',')##解压值(假设只有两列)
将({'id':row_id,'name':row_name})添加到列表中

正如darksky所提到的,在代码稳定性方面,使用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)
同样,对于朋友

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)

你是怎么让它工作的?你能包含一些有特定错误或问题的示例吗?当然,我删除了所有不起作用的代码,基本上是出于沮丧,但我尝试将列表设置为空,然后读取csv文件并创建一个for循环,以便在每次遇到迭代时尝试创建一个新字典,但我真的不知道我在做什么,或者我是否在正确的轨道上签出(尤其是
fieldnames
参数)。@Ben,这实际上也是我尝试过的。同样,没有标题也会让我很郁闷,因为在“print(row['first\u name'],row['last\u name'])”的行中,我得到了一个键error@jacknovozinsky
fieldnames
参数的全部要点是处理缺少标题的情况。它将使用您提供的列表作为标题,而不是csv的第一行。非常感谢!这回答了我的问题,为我解决了问题!我建议不要手动解析CSV,而是使用
CSV
模块。当一行包含多个逗号时,此代码将立即中断,并且还有许多其他角点情况。@darksky我完全同意对于生产应用程序而言,csv模块是一个更好的选择,我选择了我所选择的方式,因为我认为这样做更易于理解。我已经编辑了我的答案