簡體   English   中英

如何從 csv 文件創建字典列表?

[英]How can I create a list of dictionaries from a csv file?

我想為以下 csv 文件的每一行創建一個“詞典詞典”

name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5

所以這個想法是, mydict["Alice"] 應該是 {'AGATC': 2, 'AATG': 8, 'TATC': 3} 等等。

我真的不太了解 .reader 和 .DictReader 功能。 https://docs.python.org/3/library/csv.html#csv.DictReader因為我是新手,不太了解文檔。 您有其他“更簡單”的資源可以推薦嗎?

首先,我必須獲得第一列,即名稱並將它們作為鍵。 如何訪問第一列?

其次,我想在該名稱(作為值)中創建一個字典,鍵為 AGATC、AATG、TATC。 你明白我的意思嗎? 那可能嗎?

編輯,取得進展:

# Open the CSV file and read its contents into memory.
with open(argv[1]) as csvfile:
    reader = list(csv.reader(csvfile))
    # Each row read from the csv file is returned as a list of strings.
    # Establish dicts.
    mydict = {}
    for i in range(1, len(reader)):
        print(reader[i][0])
        mydict[reader[i][0]] = reader[i][1:]
    print(mydict)

出去:

{'Alice': ['2', '8', '3'], 'Bob': ['4', '1', '5'], 'Charlie': ['3', '2', '5']}

但是如何實現上面描述的嵌套字典呢?

編輯#3:

# Open the CSV file and read its contents into memory.
    with open(argv[1]) as csvfile:
        reader = list(csv.reader(csvfile))
        # Each row read from the csv file is returned as a list of strings.
        # Establish dicts.
        mydict = {}
        for i in range(1, len(reader)):
            print(reader[i][0])
            mydict[reader[i][0]] = reader[i][1:]
        print(mydict)
        
        print(len(reader))
        dictlist = [dict() for x in range(1, len(reader))]
        #for i in range(1, len(reader))
        for i in range(1, len(reader)):
            dictlist[i-1] = dict(zip(reader[0][1:], mydict[reader[i][0]]))
        #dictionary = dict(zip(reader[0][1:], mydict[reader[1][0]]))
        print(dictlist)

出去:

[{'AGATC': '2', 'AATG': '8', 'TATC': '3'}, {'AGATC': '4', 'AATG': '1', 'TATC': '5'}, {'AGATC': '3', 'AATG': '2', 'TATC': '5'}]
{'AGATC': 1, 'AATG': 1, 'TATC': 5}

所以我自己解決了:)

以下代碼將為您提供您在 dict 結構方面所要求的內容。

import csv

with open('file.csv', newline='') as csvfile:
    mydict = {}
    reader = csv.DictReader(csvfile)
    # Iterate through each line of the csv file
    for row in reader:
        # Create the dictionary structure as desired.
        # This uses a comprehension
        # Foreach item in the row get the key and the value except if the key
        # is 'name' (k != 'name')
        mydict[row['name']] = { k: v for k, v in row.items() if k != 'name' }
    print(mydict)

這會給你

{
    'Alice': {'AGATC': '2', 'AATG': '8', 'TATC': '3'},
    'Bob': {'AGATC': '4', 'AATG': '1', 'TATC': '5'},
    'Charlie': {'AGATC': '3', 'AATG': '2', 'TATC': '5'}
}

如果您需要更多關於這些的信息,網上有很多關於理解的視頻和文章。

暫無
暫無

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

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