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

标签 python csv

我有一个如下所示的 csv 文件:

enter image description here

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

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 文件:

enter image description here

我花了几个小时试图让它成为一个简单的元组列表,如下所示:

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/

相关文章:

python - 回调问题 FailedPreconditionError

php - 如何使用 PHP 从 CSV 中检索分组数据

python - 如何包含要查找的列,但将其从 GROUP BY 中排除?

python - 创建一个使用 url_for() 插入 URI 变量的 Flask 搜索栏

python - 如何在 Refextract 上一起运行多个文件

python - NumPy 的 : read data from CSV having numerals as string

R将数据帧列写入具有前导零的csv

python - 从记录中用 Pandas 索引几个 csv 文件?

mysql - 将 MySQL 输出格式化为有效的 CSV 或 XLSX

python - 将数组添加到 Pandas 数据框