簡體   English   中英

如何將CSV文件轉換為python中的字典列表

[英]How to convert CSV file into a list of dictionaries in python

我有一個如下所示的 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 文件的方法,但是我從來沒有遇到過讓我為每個條目制作一個新字典的方法,而且我認為我從來沒有處理過這樣的沒有標題的字典。 雖然我希望我可以只添加標題和我的生活更輕松,但它必須看起來像我上面給出的示例,以便我的其余代碼工作。 如果您知道如何執行此操作,請告訴我。 謝謝!

我完成了我的整個項目,但不得不對提到的字典和列表進行硬編碼,因為我根本不知道如何處理 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)

據我了解,這應該可以解決您的第一個問題。 您應該能夠輕松修改此代碼以適合您的第二個用例。

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 模塊在代碼穩定性方面可能更好,所以也看看他的回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM