从csv文件创建字典时无法迭代密钥

2024-09-29 02:15:16 发布

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

我的目标是从csv file中读取信息并将其保存到字典中(感谢注释)。字典将包含名称作为key,数字作为value。字典应是动态的,即应适用于n个行字符。所需:能够更改键值,只创建一个字典,而不是多个字典

name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5
Alice = [2,8,3]
Bob = [4,1,5]
etc.

代码也应该使用相同的逻辑来实现这一点:

name,AGATC,TTTTTTCT,AATG,TCTAG,GATA,TATC,GAAA,TCTG
Albus,15,49,38,5,14,44,14,12
Cedric,31,21,41,28,30,9,36,44
Draco,9,13,8,26,15,25,41,39
Fred,37,40,10,6,5,10,28,8
Ginny,37,47,10,23,5,48,28,23
Hagrid,25,38,45,49,39,18,42,30
Harry,46,49,48,29,15,5,28,40
Hermione,43,31,18,25,26,47,31,36
James,46,41,38,29,15,5,48,22
Kingsley,7,11,18,33,39,31,23,14
Lavender,22,33,43,12,26,18,47,41
Lily,42,47,48,18,35,46,48,50
Lucius,9,13,33,26,45,11,36,39
Luna,18,23,35,13,11,19,14,24
Minerva,17,49,18,7,6,18,17,30
Neville,14,44,28,27,19,7,25,20
Petunia,29,29,40,31,45,20,40,35
Remus,6,18,5,42,39,28,44,22
Ron,37,47,13,25,17,6,13,35
Severus,29,27,32,41,6,27,8,34
Sirius,31,11,28,26,35,19,33,6
Vernon,26,45,34,50,44,30,32,28
Zacharias,29,50,18,23,38,24,22,9

以下是我的尝试:

def readcsv(n):
    with open(f'{n}','r') as f:
        readed = csv.reader(f)
        for row in readed:
            key = row[0]
            value = row[1:]
            #print(f"{key} and {value}")
            dic = dict(key = value)
            print(dic)
OUTPUT : 
{'key': ['AGATC', 'AATG', 'TATC']}
{'key': ['2', '8', '3']}
{'key': ['4', '1', '5']}
{'key': ['3', '2', '5']}

Tags: csvkeyname目标字典valuerowbob
2条回答

你说的“name”是指变量名吗?我想这样做是可能的

globals()[row[0]] = list(row[1:])

然而,在运行时设置变量名是非常不传统的。命名空间的更好解决方案是使用字典:

rows = {row[0]:row[1:]} for row in readed}

您可以使用rows["name of row"]访问相关元素

您可以使用pandas库轻松地读入.csv文件。你要找的最好是一本字典,字典里的名字是键,列表是值

如果您有一个字典,并且想要更改某个键的值(例如,下面的dictd中的Albus),这是非常简单的

# To change the value associated with key="Albus"
d["Albus"] = [1,2,3,4,5,6,7,8]

# To access the value of key="Albus"
d["Albus"]

代码

import pandas as pd
import os # for handling file-paths
from io import StringIO # for reading dummy data

## Reading from a file "input.csv"
# df = pd.read_csv("input.csv", sep=",").set_index('name')

## Reading from the dummy data as a string
df = pd.read_csv(StringIO(s.strip()), sep=",").set_index('name')

## Subsequently process the data to get a 
# dict of structure (key=name, value=list).
df = pd.DataFrame(df.to_numpy().T, columns=df.index)
d = df.to_dict(orient='list) # returns a dictionary ==> data-structure
print(d)

输出

{'Albus': [15, 49, 38, 5, 14, 44, 14, 12],
 'Cedric': [31, 21, 41, 28, 30, 9, 36, 44],
 'Draco': [9, 13, 8, 26, 15, 25, 41, 39],
 'Fred': [37, 40, 10, 6, 5, 10, 28, 8],
 'Ginny': [37, 47, 10, 23, 5, 48, 28, 23],
 'Hagrid': [25, 38, 45, 49, 39, 18, 42, 30],
 'Harry': [46, 49, 48, 29, 15, 5, 28, 40],
 'Hermione': [43, 31, 18, 25, 26, 47, 31, 36],
 'James': [46, 41, 38, 29, 15, 5, 48, 22],
 'Kingsley': [7, 11, 18, 33, 39, 31, 23, 14],
 'Lavender': [22, 33, 43, 12, 26, 18, 47, 41],
 'Lily': [42, 47, 48, 18, 35, 46, 48, 50],
 'Lucius': [9, 13, 33, 26, 45, 11, 36, 39],
 'Luna': [18, 23, 35, 13, 11, 19, 14, 24],
 'Minerva': [17, 49, 18, 7, 6, 18, 17, 30],
 'Neville': [14, 44, 28, 27, 19, 7, 25, 20],
 'Petunia': [29, 29, 40, 31, 45, 20, 40, 35],
 'Remus': [6, 18, 5, 42, 39, 28, 44, 22],
 'Ron': [37, 47, 13, 25, 17, 6, 13, 35],
 'Severus': [29, 27, 32, 41, 6, 27, 8, 34],
 'Sirius': [31, 11, 28, 26, 35, 19, 33, 6],
 'Vernon': [26, 45, 34, 50, 44, 30, 32, 28],
 'Zacharias': [29, 50, 18, 23, 38, 24, 22, 9]}

虚拟数据

s = """
name,AGATC,TTTTTTCT,AATG,TCTAG,GATA,TATC,GAAA,TCTG
Albus,15,49,38,5,14,44,14,12
Cedric,31,21,41,28,30,9,36,44
Draco,9,13,8,26,15,25,41,39
Fred,37,40,10,6,5,10,28,8
Ginny,37,47,10,23,5,48,28,23
Hagrid,25,38,45,49,39,18,42,30
Harry,46,49,48,29,15,5,28,40
Hermione,43,31,18,25,26,47,31,36
James,46,41,38,29,15,5,48,22
Kingsley,7,11,18,33,39,31,23,14
Lavender,22,33,43,12,26,18,47,41
Lily,42,47,48,18,35,46,48,50
Lucius,9,13,33,26,45,11,36,39
Luna,18,23,35,13,11,19,14,24
Minerva,17,49,18,7,6,18,17,30
Neville,14,44,28,27,19,7,25,20
Petunia,29,29,40,31,45,20,40,35
Remus,6,18,5,42,39,28,44,22
Ron,37,47,13,25,17,6,13,35
Severus,29,27,32,41,6,27,8,34
Sirius,31,11,28,26,35,19,33,6
Vernon,26,45,34,50,44,30,32,28
Zacharias,29,50,18,23,38,24,22,9
"""

相关问题 更多 >