如何在推入新项目时保持字典排序?
How to keep a dict sorted as new items are pushed in?
所以我有一个这样的高分文件:
Markus:5000
Mike:3000
John:2400
然后我读给 OrderdDict
:
high_scores = OrderedDict()
with open('highscores.txt') as file:
for line in file:
name, score = line.strip().split(':')
high_scores[name] = int(score)
现在,当我向字典中添加新乐谱时,我该如何保持排序?我想到的唯一方法是每次都用这样的东西重新创建字典:
high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True)
high_scores = OrderedDict(high_scores)
但这看起来相当糟糕,如果在将元素添加到字典时将它们放在正确的位置,我会更愿意,即我希望始终保持字典排序。
OrderedDict 不是高分列表的最佳结构。尝试使用常规的 2 元组列表,每次添加元素时只需 sort()
它。
如果你真的不喜欢显式排序,你可以使用 https://pypi.python.org/pypi/sortedcontainers 为你做。
所以我有一个这样的高分文件:
Markus:5000
Mike:3000
John:2400
然后我读给 OrderdDict
:
high_scores = OrderedDict()
with open('highscores.txt') as file:
for line in file:
name, score = line.strip().split(':')
high_scores[name] = int(score)
现在,当我向字典中添加新乐谱时,我该如何保持排序?我想到的唯一方法是每次都用这样的东西重新创建字典:
high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True)
high_scores = OrderedDict(high_scores)
但这看起来相当糟糕,如果在将元素添加到字典时将它们放在正确的位置,我会更愿意,即我希望始终保持字典排序。
OrderedDict 不是高分列表的最佳结构。尝试使用常规的 2 元组列表,每次添加元素时只需 sort()
它。
如果你真的不喜欢显式排序,你可以使用 https://pypi.python.org/pypi/sortedcontainers 为你做。