Python 按dictionary的值对字典列表进行排序?TypeError:字符串索引必须是整数
我编写了一个Python脚本,允许我在文件中检索一些信息,如e值、登录次数。。。然后我将这些信息存储在字典中Python 按dictionary的值对字典列表进行排序?TypeError:字符串索引必须是整数,python,sorting,dictionary,key,key-value,Python,Sorting,Dictionary,Key,Key Value,我编写了一个Python脚本,允许我在文件中检索一些信息,如e值、登录次数。。。然后我将这些信息存储在字典中 import operator file = open("4.A.1.1.3.txt", "r") line = file.readline() dico_hit = dict() for line in file : if '#' not in line : columns = line.split()
import operator
file = open("4.A.1.1.3.txt", "r")
line = file.readline()
dico_hit = dict()
for line in file :
if '#' not in line :
columns = line.split()
query = columns[3]
accession = columns[4]
evalue = columns[6]
hmmfrom = int(columns[15])
hmmto = int(columns[16])
dico_hit[query] = {'Accession' : accession, 'E-value' : evalue,'Hmmfrom' : hmmfrom, 'Hmmto' : hmmto}
以下是我的字典预览:
PTS_EIIB {'Accession': 'PF00367.21', 'E-value': '4.9e-21', 'Hmmfrom': '2', 'Hmmto': '34'}
PTS_EIIC {'Accession': 'PF02378.19', 'E-value': '8.9e-92', 'Hmmfrom': '1', 'Hmmto': '324'}
我想按一个字典值(E值)对字典列表进行排序。为此,我使用函数“sorted”
我犯了这样的错误:
TypeError: string indices must be integers
我不明白是什么导致了这个错误?这不是正确的方法吗?dico\u hit不是一个列表,而是一个dict,如果你想对它们进行排序,你应该使用list。因此,在循环之前:
dico_hit = list()
然后像这样附加到列表,而不是dico_hit[query]={'Ac..
:
dico_hit.append({'Accession' : accession, 'E-value' : evalue,'Hmmfrom' : hmmfrom, 'Hmmto' : hmmto})
然后您的sorted
函数就可以正常工作了
顺便说一下:
由于字典的基本实现,无法对其进行排序。要对字典进行排序,可以使用集合。OrderedDict
您没有字典列表,但正在尝试对字典进行排序。当您进行迭代时,它会迭代字典的键,这些键是字符串。您正在尝试使用
'E-value'
对这些字符串进行索引。字典无法排序。如果您希望以这种方式对键/值对进行排序,可以使用排序(dico_hit.items(),key=lambda x:x[1]['E-value'])
。是的,你说得对。我想要一个键和值的排序列表。你的方法很有效。谢谢你的帮助。
dico_hit.append({'Accession' : accession, 'E-value' : evalue,'Hmmfrom' : hmmfrom, 'Hmmto' : hmmto})