python - 在Python中按值对多个字典进行排序

标签 python sorting dictionary

我正在尝试按降序对 Python 中的多个字典进行排序。

highs = []
file_a = open("/home/victor/Documents/Python-3.5.1/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4413761b74040d05066a071712" rel="noreferrer noopener nofollow">[email protected]</a>")
def func():
    for line in file_a:
        from collections import OrderedDict
        s = {}
        (s['date'], s['open'], s['high'], s['low'], s['close'],    s['volume'], s['openinterest'], s['totalVolume'], s['totalOpenInterest']) = line.split(',')
    newlist = sorted(s.items(), key=lambda s: float(s[2]), reverse = True)

func()
file_a.close()

但是,每次运行它时我都会收到此错误:

File "/home/victor/Documents/first project.py", line 8, in <lambda>
newlist = sorted(s.items(), key=lambda s: float(s[2]), reverse = True)
IndexError: tuple index out of range

我对 Python 很陌生。任何帮助将不胜感激。

最佳答案

您的代码遇到的一个问题是它会迭代整个文件,重复创建名为 s 的字典对象。 ,但在创建下一个之前不会对每个它们执行任何操作(最后一个除外,见下文)。

该错误消息是因为在创建并忽略所有这些字典后,尝试对 s.items() 中的值进行排序。执行此操作的读取循环完成后。这意味着s将保留最后创建的字典(从文件的最后一行开始)。无论如何,s.items()是字典的(键,值)对列表的副本,其中可能包含以下内容:

[('volume', '300000'), ('high', '110'), ('low', '90') ('totalOpenInterest', '4.56'),
 ('date', '01/01/16'), ('close', '101'), ('openinterest', '.99'), ('open', '100'),
 ('totalVolume', '1000000')]

由于此列表的每一项中只有两件事 - 每一项都被命名为 s,这有点令人困惑。 lambda参数函数 — 所以 float(s[2])在您的代码中会引发 IndexError因为2大于 1 的最高有效索引对于每一对值。

我认为下面的代码正确地完成了您想要完成的任务。它首先存储每个 s在名为 data 的临时列表中创建的词典,然后根据其键 ( 'high' ) 引用的每个值之一对其进行排序。

from operator import itemgetter

def func(filename):
    keys = ('date open high low close volume openinterest totalVolume '
            'totalOpenInterest').split()
    data = []
    with open(filename) as file_a:
        for line in file_a:
            s = dict(zip(keys, line.rstrip().split(',')))
            data.append(s)

    return sorted(data, key=lambda x: float(itemgetter('high')(x)), reverse=True)


filename = "/home/victor/Documents/Python-3.5.1/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d4a2f422d5d545c5f335e4e4b" rel="noreferrer noopener nofollow">[email protected]</a>"
sorted_dicts = func(filename)
for d in sorted_dicts:
    print(d)

关于python - 在Python中按值对多个字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820007/

相关文章:

python - 删除嵌套列表中的重复项(不删除子列表中的重复元素)

c++ - 为什么我的程序在选择排序功能后暂停?

java - CountDiv (Codility) 挑战算法的性能问题

Python:如何使用原始列表中的某些按字母顺序排列的项目创建新列表?

python - python 新手从文件创建两个字典需要特定行

java - 无法在其他方法中检索 HashMap 输入

python - 将字符串放在Python中的字符串旁边

python - 检测源代码中的 SQL 注入(inject)

python - 数据帧 : Group separate subcolumns with identical column names together

python - 查找列表中的哪个元素是字典中的键以及它的值是什么