【发布时间】:2016-04-05 15:03:53
【问题描述】:
这就是我要完成的工作:输入与定义字典中的键对应的项目的文本文件列表,让程序打印该列表中所有键的所有值。如您所见,字典设置为包含每个键的多个值。字典可以很好地报告单个键的值,但我在尝试让它报告多个键的值(在文本文件列表中定义)时遇到问题。
代码如下:
# open the text file containing a list that will be looked up in the dictionary below
with open('/home/matt/Source/python/fpkm-batch-lookup/lookuplist.txt', 'r') as lookupfile:
lookup = str(lookupfile.read().splitlines())
# define output file
output = open('/home/matt/Source/python/fpkm-batch-lookup/output.csv', 'w')
# assign keydict dictionary keys and values as columns in input file
keydict = {}
data = open('/home/matt/Source/python/fpkm-lookup/input.csv', 'r')
for line in data:
items = line.rstrip('\n').split(',')
key, values = items[0], items[1:]
keydict[key] = values
# write out key and values to output file
output.write(lookup + '\n' + str(keydict['Alt Name']) + '\n' + str(keydict[lookup]) + '\n')
尝试运行它,它返回:
Traceback (most recent call last):
File "/home/matt/Source/python/fpkm-batch-lookup/run.py", line 17, in <module>
output.write(lookup + '\n' + str(keydict['Alt Name']) + '\n' + str(keydict[lookup]) + '\n')
KeyError: "['ENSG00000196476_C20orf96', 'ENSG00000247315_ZCCHC3', 'ENSG00000225377_RP5-1103G7.4', 'ENSG00000177732_SOX12', 'ENSG00000101255_TRIB3']"
KeyError 消息中列出的项目是查找列表文本文件中的项目。我的代码是否将整个查找列表文件视为查找的关键?我怎么能让它把这个文件中的每一行都当作一个键来查找呢?
谢谢!
编辑/更新:
使用 [0]、[1] 等来指定要查找的每个键然后写入输出文件的相当不雅的方法。这是我使用的最终代码:
# open the text file containing a list that will be looked up in the dictionary below
lookuplist = open('/home/matt/Source/python/fpkm-batch-lookup/lookuplist.txt').read().splitlines()
# define output file
output = open('/home/matt/Source/python/fpkm-batch-lookup/output.csv', 'w')
# assign keydict dictionary keys and values as columns in input file
keydict = {}
data = open('/home/matt/Source/python/fpkm-lookup/input.csv', 'r')
for line in data:
items = line.rstrip('\n').split(',')
key, values = items[0], items[1:]
keydict[key] = values
# write out key and values to output file - add more if needed
output.write(str(lookuplist[0]) + '\n' + str(keydict['Alt Name']) + '\n' + str(keydict[lookuplist[0]]) + '\n' + '\n')
output.write(str(lookuplist[1]) + '\n' + str(keydict['Alt Name']) + '\n' + str(keydict[lookuplist[1]]) + '\n' + '\n')
output.write(str(lookuplist[2]) + '\n' + str(keydict['Alt Name']) + '\n' + str(keydict[lookuplist[2]]) + '\n' + '\n')
# .... to the nth string number to lookup
我想我会更新,给其他想做同样事情的人。
【问题讨论】:
-
首先观察,从文件中读取的内容将是一个字符串,因此您不必将其字符串化 str(lookupfile.read().splitlines())
-
当我看到“['ENSG00000196476_C20orf96', 注意双引号
-
从查找中删除 str() = 返回一个 TypeError: can only concatenate list (not "str") to list ... 所以这就是我将 str() 扔进去的原因。
-
引用的是什么行号
-
我很确定这是因为您没有一次引用查找中的项目,请查看下面的代码
标签: python list dictionary key