如何让字典保持有序

使用标准库collections中的OrderedDict

以OrderedDict替代内置字典Dict,依次将选手成绩存入OrderedDict

from collections import OrderedDict
od = OrderedDict()
od['c'] = 1
od['b'] = 2
od['a'] = 3
list(iter(od))

执行结果:

['c', 'b', 'a']
from collections import OrderedDict
od = OrderedDict()
# 制造数据
players = list('abcdefgh')
from random import shuffle
shuffle(players) #洗牌函数,将列表打乱
for i, p in enumerate(players, 1):
    od[p] = i

def query_by_name(d, name):
    return d[name]

query_by_name(od, 'e') #查询e的名次

from itertools import islice #为可迭代对象制作切片
def query_by_order(d, a, b = None):
    a -= 1
    if b is None:
        b = a + 1
    return list(islice(od, a, b))

print(od)
query_by_order(od, 4, 6)

执行结果:

OrderedDict([('f', 1), ('h', 2), ('a', 3), ('e', 4), ('d', 5), ('c', 6), ('b', 7), ('g', 8)])
['e', 'd', 'c']

你可能感兴趣的:(如何让字典保持有序)