如何让字典保持有序?

Posted richardo-m-q

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何让字典保持有序?相关的知识,希望对你有一定的参考价值。

需求:
某编程竞赛系统,对参赛选手编程解题进行计时,选手完成题目后,把该选手的解题用时记录到字典中,以便赛后按选手名查看选手成绩
{‘lilei‘:(2,43),‘HanMeiMei‘:(5,52),‘Jim‘:(1,39)..}
比赛结束后,需按排名顺序依次打印选手成绩,如何实现?

思路:
使用标准库中的collections中的OrderDict
以OrderDict代替内置字典dict,依次将选手的成绩存入OrderDict
ps:python3.6中的内置字典已经为有序字典,3.6之前为无序字典

代码:

>>> d = {}

>>> d[‘c‘] = 1

>>> d[‘b‘] = 2

>>> d[‘a‘] = 3

>>> d.keys()
dict_keys([‘c‘, ‘b‘, ‘a‘])

>>> list(iter(d))
[‘c‘, ‘b‘, ‘a‘]

>>> from collections import OrderedDict

>>> od = OrderedDict()

>>> od[‘c‘] = 1

>>> od[‘b‘] = 2

>>> od[‘a‘] = 3

>>> od.keys()
odict_keys([‘c‘, ‘b‘, ‘a‘])

>>> player = list(‘abcdefg‘)

>>> from random import shuffle

>>> shuffle(player)

>>> player
[‘d‘, ‘c‘, ‘f‘, ‘e‘, ‘b‘, ‘a‘, ‘g‘]

>>> od = OrderedDict()

>>> for i,p in enumerate(player,1):
...     od[p] = i
... 

>>> od
OrderedDict([(‘d‘, 1),
             (‘c‘, 2),
             (‘f‘, 3),
             (‘e‘, 4),
             (‘b‘, 5),
             (‘a‘, 6),
             (‘g‘, 7)])

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

>>> query_by_name(od,f)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-67-eb4396f2d4db> in <module>
----> 1 query_by_name(od,f)

NameError: name ‘f‘ is not defined

>>> query_by_name(od,‘f‘)
3

>>> iter(od)[3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-996216e64316> in <module>
----> 1 iter(od)[3]

TypeError: ‘odict_iterator‘ object is not subscriptable

>>> iter(od)[3:5]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-a9879548c137> in <module>
----> 1 iter(od)[3:5]

TypeError: ‘odict_iterator‘ object is not subscriptable

>>> from itertools import islice

>>> islice(range(10),3,6)
<itertools.islice at 0x7f3ae39bb868>

>>> range(10)
range(0, 10)

>>> iter(range(10))
<range_iterator at 0x7f3ae3f72a20>

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(iter(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(islice(range(10),3,6))
[3, 4, 5]

>>> list(islice(od,3,6))
[‘e‘, ‘b‘, ‘a‘]

>>> def query_by_order(d,a,b=None):  # 按名次来取,
...     a -= 1 # 默认从0开始切片
...     if b is None:
...         b = a + 1  # 取一个的情况
...     return list(islice(od,a,b))
... 

>>> od
OrderedDict([(‘d‘, 1),
             (‘c‘, 2),
             (‘f‘, 3),
             (‘e‘, 4),
             (‘b‘, 5),
             (‘a‘, 6),
             (‘g‘, 7)])

>>> query_by_order(od,4)
[‘e‘]

>>> query_by_order(od,3,6)
[‘f‘, ‘e‘, ‘b‘, ‘a‘]






以上是关于如何让字典保持有序?的主要内容,如果未能解决你的问题,请参考以下文章

如何让字典保持有序

python 如何让字典保持有序

如何让字典保持有序?

问题6:如何让字典保持有序(使用collections的OrderedDict方法)

Python强化训练笔记——让字典保持有序性

Python实用技法第6篇:让字典保持有序