每行的Python csv到字典

2024-06-17 14:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

enter image description here

我希望结果如下所示:

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

档案中每一行的字典。 我试着使用CSV.DictReader,但我没有任何运气。非常感谢您的任何意见/提示


Tags: 文件csvnameimage字典here档案description
2条回答

除了“运气不佳”之外,你到底有什么问题

此外,我认为你应该考虑使用嵌套的DICT或列表。我不确定您是否可以通过从文件中加载新的代码变量来自动创建它们。无论如何,你想如何与他们合作

例如:

peoples = {'Alice': {'AGATC': 2, 'AATG': 8, 'TATC': 3},
           'Bob': {...}}

此外,您可以尝试使用csv.reader()

with Path.open(csv_file) as file:
    reader = csv.reader(file, delimiter=',')
    for i, row in enumerate(reader):
        if i == 0:
            # first csv-line. Find the structure of your dict here
            # or ignore it and hard-code it
        else:
            # values of the row can be accessed as list 

这可能会满足您的要求,但我个人会使用列表(dict)数据结构:

import csv
import json

def open_csv(path):
    '''return a list of dictionaries
    '''
    with open(path, 'r') as file:
        reader = csv.DictReader(file)
        return [dict(row) for row in reader]

data_list = open_csv('data.csv')

data_dict = {item['name']:
             {k: v for k, v in item.items()
              if k != 'name'}
             for item in data_list}

print('list of dict:')
print(json.dumps(data_list, indent=4))
print('dict of dict:')
print(json.dumps(data_dict, indent=4))

输出:

list of dict:
[
    {
        "name": "Alice",
        "AGATC": "2",
        "AATG": "8",
        "TATC": "3"
    },
    {
        "name": "Bob",
        "AGATC": "4",
        "AATG": "1",
        "TATC": "5"
    },
    {
        "name": "Charlie",
        "AGATC": "3",
        "AATG": "2",
        "TATC": "5"
    }
]
dict of dict:
{
    "Alice": {
        "AGATC": "2",
        "AATG": "8",
        "TATC": "3"
    },
    "Bob": {
        "AGATC": "4",
        "AATG": "1",
        "TATC": "5"
    },
    "Charlie": {
        "AGATC": "3",
        "AATG": "2",
        "TATC": "5"
    }
}

相关问题 更多 >