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

用户11122284

我有一个如下所示的 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)]

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!

nathan.medz

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

正如darksky所提到的,使用 csv 模块在代码稳定性方面可能更好,所以也看看他的回答

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将CSV文件转换为python字典

如何将CSV文件转换为python中的列表列表

如何将字典中的列表转换为列表中的字典(Python)

如何将此字典列表转换为csv文件?

如何将此字典列表转换为表或csv文件?

如何将字典列表转换为 csv?

Python如何将字典列表转换为元组列表

使用Python将列表字典转换为CSV文件

将字典列表转换为CSV文件

哈斯克尔 | 如何将 CSV 文件中的数字列表转换为包含列表的列表

Python:如何将元组列表转换为字典键?

如何将列表元素转换为字典/元组?Python

如何将二维列表转换为python中的字典列表?

如何将列表转换为字典

如何将列表转换为字典

如何将字典中的字符串值转换为python中的列表?

在Python 3中将字典列表转换为CSV

如何将csv文件中的列表列表转换为numpy数组

如何将.txt文件中的列表转换为python文件中的列表?

如何将py2neo.database.cursor类转换为python中的字典或列表?

将CSV文件转换为Python字典

如何将.txt文件中的列表转换为处理(python)中的列表?

如何将python数组(列表)转换为CSV

如何将JSON列表转换为CSV文件中的两个不同列?

如何将字典中的字典列表转换为仅值列表?

如何将字典列表转换为列表列表?

如何使用键值将列表转换为python中的字典?

如何将字典列表转换为字典

如何将位于文件中的列表转换为我可以在 python 中使用的列表?