我有一个如下所示的 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!
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] 删除。
我来说两句