python学习--如何让字典变的有序

使用collections模块下的OrderedDict,可以使字典中的数据按照存放的顺序取出来,一般的字典存放数据是无序的。

模拟一个OrderedDict存入取出的过程。

from time import time
from random import randint
from collections import OrderedDict


person=list('ABCDEFGH')  #创建一个人员列表['A','B','C','D','E','F','G','H']
start=time() #创建开始时间
od=OrderedDict() #创建有序集合
for i in range(8): #创建一个循环8次
  input() #每次回车,就往od这有序字典中存入相关信息
  p=person.pop(randint(0,7-i))
  end=time()
  print(p,i+1,end-start)
  od[p]=(i+1,end-start)
print('----------')
for x in od:
  print(x,od[x])

原文地址:https://www.cnblogs.com/daacheng/p/7912642.html