【问题标题】:Not able to iterate key while creating a dictionary out of a csv file从 csv 文件创建字典时无法迭代键
【发布时间】:2020-06-10 17:27:40
【问题描述】:

我的目标是从csv file 读取信息并将其保存到字典中(感谢 cmets)。字典将包含名称为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']}

【问题讨论】:

  • 您不应该动态创建变量,而是使用容器,可能是dict,将名称作为字符串映射到其余数据
  • 我对 dict 的问题是:他们每 1 个值只能获得 1 个键,我试图为值创建一个元组。但是出现了同样的语法错误。 @juanpa.arrivillaga
  • 你应该使用列表的字典,而不是元组。无论如何,那是因为您的最后一行有语法错误,这与我所说的无关。有几件可疑的事情正在发生。例如,您在每次迭代 上使用next(reader),这将导致您的循环跳过所有其他元素,而不仅仅是标题。 name = row[0] 是没有意义的,因为你立即用name = [for i in row[1:]] 跟随它,我不知道你的意思是什么,你可能只是说name = row[1:]
  • 如果我错了,请纠正我,但我读到字典应该由不可变对象创建,这就是我尝试元组的原因。 @juanpa.arrivillaga
  • 你需要一个字典,其中 key=name, value=list。

标签: python list csv


【解决方案1】:

您可以使用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
"""

【讨论】:

  • 它看起来不错,但我想为了课程的缘故,我将使用数据结构的实现而不是 pandas。感谢您的帮助。
  • 你这里的数据结构是一个字典。如果你能解释你的需求/设计限制,也许我能更好地理解你的需求。
  • @IDK 如果您认为该解决方案有帮助,请考虑 voting-upaccepting(如果适用)。谢谢。
  • 好的,请检查以下版本的问题,谢谢。
  • 我检查了你最后添加的内容。为什么所有的键都叫"key"?为什么要创建多个字典?
【解决方案2】:

“name”是指变量名吗?我想有可能做这样的事情

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

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

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

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

【讨论】:

  • 不需要ilist(row[1:]) 可以是row[1:],不要再无谓地调用列表...
猜你喜欢
  • 2016-09-03
  • 2011-10-08
  • 2012-12-15
  • 2012-01-02
  • 2016-11-22
相关资源
最近更新 更多