【问题标题】:Sort a list dictionaries by a value of dictionary? TypeError: string indices must be integers按字典的值对列表字典进行排序? TypeError:字符串索引必须是整数
【发布时间】:2020-11-10 22:03:49
【问题描述】:

我编写了一个 Python 脚本,允许我在文件中检索一些信息,例如电子值、加入数……然后我将这些信息存储在字典中。

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 值)对字典列表进行排序。为此,我使用“排序”功能。

sort_evalue= sorted(dico_hit, key=lambda k: k['E-value'])
print(sort_evalue)

我弄错了:

TypeError: string indices must be integers

我不明白是什么导致了这个错误?这难道不是正确的做法吗?

【问题讨论】:

  • 您没有字典列表,但正在尝试对字典进行排序。当您进行迭代时,它会迭代字典的键,即字符串。您正在尝试使用 'E-value' 索引这些字符串。
  • 字典无法排序。如果您想要以这种方式排序的键/值对列表,您可以使用sorted(dico_hit.items(), key=lambda x: x[1]['E-value'])
  • 是的,你是对的。我想要一个键和值的排序列表。你的方法有效。感谢您的帮助。

标签: python sorting dictionary key key-value


【解决方案1】:

dico_hit 不是一个列表,它是一个dict,如果你想对它们进行排序,你应该使用列表。所以在你的循环之前:

dico_hit = list()

然后附加到这样的列表中,dico_hit[query] = {'Ac...:

dico_hit.append({'Accession' : accession, 'E-value' : evalue,'Hmmfrom' : hmmfrom, 'Hmmto' : hmmto})

那么你的sorted 函数就可以正常工作了。

顺便说一句:

由于字典的基本实现,您无法对字典进行排序。要订购字典,您可以使用collections.OrderedDict

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2020-08-24
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    相关资源
    最近更新 更多