Python2 下如何使字典保持有序排列

版权声明:欢迎转载,总结并分享是进步的源泉和动力。 https://blog.csdn.net/GIS_BT/article/details/85034447
# 使用collections中OrderedDict使字典保持有序
d = {}

d['Jim'] = (1,35)

d['Bob'] = (2,37)

d['Leo'] = (3,40)

for k in d: print k

from collections import OrderedDict

d = OrderedDict()

d['Jim'] = (1,35)

d['Bob'] = (2,37)

d['Leo'] = (3,40)

for k in d: print k

#~~~~~实际案例:模拟竞赛系统加深印象

from time import time
from random import randint
from collections import OrderedDict
players = list('ABCDEFGH')
d = OrderedDict()
start = time()
for i in xrange(8):
    raw_input()
    p=players.pop(randint(0,7-i))
    end = time()
    print i + 1,p,end - start
    d[p]=(i+1,p,end-start)

print '-'*20

for k in d:
 print k,d[k]

猜你喜欢

转载自blog.csdn.net/GIS_BT/article/details/85034447