简体   繁体   English

在Python(2.4)字典中排序

[英]Ordering in Python (2.4) dictionary

    r_dict={'answer1': "value1",'answer11': "value11",'answer2': "value2",'answer3': "value3",'answer4': "value4",}

    for i in r_dict:
        if("answer" in i.lower()):
           print i

  Result is answer11,answer2,snswer4,answer3

I am using Python 2.4.3. 我正在使用Python 2.4.3。 I there any way to get the order in which it is populated? 我有什么方法可以获取填充顺序?

Or is there a way to do this by regular expression since I am using the older Python version? 还是因为我使用的是旧版Python,所以可以通过正则表达式来做到这一点吗?

Dictionaries are unordered - that is, they do have some order, but it's influenced in nonobvious ways by the order of insertion and the hash of the keys. 字典是无序的-也就是说,它们确实有一定的顺序,但是它以非显而易见的方式受到插入顺序和键的散列的影响。 However, there is another implementation that remembers the order of insertion, collections.OrderedDict . 但是,还有一个记住插入顺序的实现,即collections.OrderedDict

Edit: For Python 2.4, there are several third party implementations. 编辑:对于Python 2.4,有几个第三方实现。 I haven't used any, but since the one from voidspace looks promising. 我没有用过,但是由于voidspace中的那个看起来很有希望。

Not just by using the dictionary by itself. 不只是通过单独使用字典。 Dictionaries in Python (and a good portion of equivalent non-specialized data structures that involve mapping) are not sorted. Python中的字典(以及相当一部分涉及映射的等效非专业数据结构)未排序。

You could potentially subclass dict and override the __setitem__ and __delitem__ methods to add/remove each key to an internal list where you maintain your own sorting. 您可以将dict子类化,并覆盖__setitem____delitem__方法,以将每个键添加/删除到内部列表中,以维护自己的排序。 You'd probably then have to override other methods, such as __iter__ to get the sorting you want out of your for loop. 然后,您可能必须重写其他方法,例如__iter__ ,才能从for循环中获得所需的排序。

...or just use the odict module as @delnan suggested ...或者只是按照@delnan的建议使用odict模块

A dictionary is by construction unordered. 字典是无序构造的。 If you want an ordered one, use a collections.OrderedDict : 如果您要订购,请使用collections.OrderedDict

import collections
r_dict = collections.OrderedDict( [ ( 'answer1', "value1"), ('answer11', "value11"), ('answer2', "value2"), ('answer3', "value3"), ('answer4', "value4") ] )

for i in r_dict:
    if("answer" in i.lower()):
        print i 

Short answer: no. 简短的回答:不。 Python dictionaries are fundamentally unordered. Python字典从根本上说是无序的。

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

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