Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在推送新项目时对dict进行排序?_Python_Python 3.x_Sorting_Dictionary_Ordereddictionary - Fatal编程技术网

Python 如何在推送新项目时对dict进行排序?

Python 如何在推送新项目时对dict进行排序?,python,python-3.x,sorting,dictionary,ordereddictionary,Python,Python 3.x,Sorting,Dictionary,Ordereddictionary,因此,我有一个高分文件,如下所示: Markus:5000 Mike:3000 John:2400 high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True) high_scores = OrderedDict(high_scores) 我把它读给一个OrderdDict: high_scores = OrderedDict() with open('highscores.txt') as file

因此,我有一个高分文件,如下所示:

Markus:5000
Mike:3000
John:2400
high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True)
high_scores = OrderedDict(high_scores)
我把它读给一个
OrderdDict

high_scores = OrderedDict()
with open('highscores.txt') as file:
    for line in file:
        name, score = line.strip().split(':')
        high_scores[name] = int(score)
现在,当我在字典中添加新分数时,我如何保持它的排序?我想到的唯一方法就是每次都用这样的东西重新创建字典:

Markus:5000
Mike:3000
John:2400
high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True)
high_scores = OrderedDict(high_scores)

但这似乎是相当糟糕的行为,我更希望在我将元素添加到字典时将它们放在正确的位置,即,我希望字典始终保持排序。

OrderedDict不是高分列表的最佳结构。尝试常规的2元组列表,每次添加元素时只需对其进行
sort()


如果你真的不喜欢显式排序,你可以用它来帮你。

对于高分列表来说,OrderedDict不是最好的结构。尝试常规的2元组列表,每次添加元素时只需对其进行
sort()


如果你真的不喜欢显式排序,你可以使用它来做。

如果你想保留排序顺序,你可能想考虑一个可选的数据结构,比如优先级队列。<代码>排序< /代码> ING,因为算法TIMORE的工作方式,每一次可能不像它听起来那么糟,而且它是在C中完成的,但是像约翰建议的那样排序instead@Chris_Rands或者可以使用
对分
库…@JonClements是的,这实际上更好我想如果你想保持排序顺序,你可能想考虑一个可选的数据结构,比如优先级队列。<代码>排序< /COD> >每次它可能不像它的声音那么差,因为算法TIMORE是有效的,它也是在C中完成的,但是像约翰建议的那样排序instead@Chris_Rands或者可以使用
对分
库…@JonClements是的,我认为这实际上更好