繁体   English   中英

如何使字典的值按字母顺序显示

[英]how to make the values of dictionary appear in alphabetical order

假设我有这本字典:

{'song': 1, 'like': 1, 'most': 1, 'neer': 1, 'hides': 1, 'live': 1, 'yours': 1, 'come': 2, 'not': 1, 'rage': 1, 'deserts': 1, 'be': 2, 'graces': 1, 'metre': 1, 'rights': 1, 'tomb': 1, 'stretched': 1, 'verse': 1, 'write': 1, 'the': 2, 'beauty': 1, 'all': 1, 'should': 2, 'it': 3, 'rhyme': 1, 'is': 1, 'this': 1, 'in': 4, 'earthly': 1, 'numbers': 1, 'to': 2, 'if': 2, 'my': 3, 'yet': 1, 'less': 1, 'would': 1, 'life': 1, 'an': 1, 'alive': 1, 'number': 1, 'a': 2, 'child': 1, 'say': 1, 'tongue': 1, 'heavenly': 1, 'knows': 1, 'men': 1, 'could': 1, 'half': 1, 'so': 1, 'parts': 1, 'their': 1, 'high': 1, 'with': 2, 'believe': 1, 'such': 1, 'that': 1, 'papers': 1, 'eyes': 1, 'antique': 1, 'age': 2, 'were': 2, 'fresh': 1, 'lies': 1, 'than': 1, 'poet': 1, 'termed': 1, 'old': 1, 'touches': 1, 'and': 5, 'but': 2, 'some': 1, 'of': 4, 'time': 2, 'touched': 1, 'twice': 1, 'will': 1, 'yellowed': 1, 'you': 1, 'though': 1, 'heaven': 1, 'poets': 1, 'truth': 1, 'who': 1, 'i': 1, 'faces': 1, 'which': 1, 'scorned': 1, 'shows': 1, 'filled': 1, 'your': 6, 'true': 1, 'as': 1}

如何使每个键值对按键字母顺序排序?

我试着做:

for key,value in sorted(freqs.items()):
        freqs[key]=value

但这无能为力。 我希望它看起来像这样:ab 5和8 ...你的2

Dict不是经过排序的数据结构,但是您可以使用以下方式对它们进行遍历:

for key in sorted(freqs.keys()):
        print freqs[key]

collections.OrderedDict用于此目的。 范例

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

Python中的字典本质上是未排序的。 如果要在两个不同的地方两次调用字典,则可以期望它们的顺序不同。 除非我理解不对?

尝试以下方法之一:

挖土是树和堆的混合体。 它的工作方式类似于排序的(按键)字典。

红黑树是一棵树。 它也像按字典排序的字典一样工作。

有人说,采伐平均比红黑树要快,但是采伐在操作时间上有更大的标准差。

除了排序外,它们都几乎在O(logn)时间内完成所有操作。 他们都将所有事情按关键,不停地排序。

有时最好对标准字典的键进行排序,但在循环内进行排序却不是一个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM