Hulk
Hulk

Reputation: 34160

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. 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?

Upvotes: 0

Views: 1044

Answers (4)

whaley
whaley

Reputation: 16265

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.

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. You'd probably then have to override other methods, such as __iter__ to get the sorting you want out of your for loop.

...or just use the odict module as @delnan suggested

Upvotes: 1

user395760
user395760

Reputation:

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.

Edit: For Python 2.4, there are several third party implementations. I haven't used any, but since the one from voidspace looks promising.

Upvotes: 2

Katriel
Katriel

Reputation: 123622

A dictionary is by construction unordered. If you want an ordered one, use a 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 

Upvotes: 1

Ethan Shepherd
Ethan Shepherd

Reputation: 569

Short answer: no. Python dictionaries are fundamentally unordered.

Upvotes: 0

Related Questions