views:

81

answers:

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

A: 

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 http://www.voidspace.org.uk/python/odict.html as @delnan suggested

whaley
A: 

Short answer: no. Python dictionaries are fundamentally unordered.

Ethan Shepherd
+1  A: 

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 
katrielalex
I am using python 2.4.3 i think this may not be possible
Hulk
`collections` was introduced in Python 2.4, I believe. Have you tried it?
katrielalex
Ah, apologies. `collections` was indeed introduced in Python 2.4, but `OrderedDict` wasn't added until 2.7. If you need this functionality, it's probably easiest to make a list of [(key, value)] tuples and handle uniqueness yourself.
katrielalex
+2  A: 

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.

delnan
he's on python 2.4.3. OrderedDict is new as of 2.7.
whaley
Yeah, already saw that and added a 2.4 solution.
delnan
+1 for voidspace's implementation. I wasn't aware of that previously.
whaley
A: 

with your old version of python, you should still sort your dictionnary with a lamba fonction...

it's not what you ask but four your example it's not far from what you expect:

>>> sorted(r_dict.iteritems(),key=lambda x: x[1]) [('answer1', 'value1'), ('answer11', 'value11'), ('answer2', 'value2'), ('answer3', 'value3'), ('answer4', 'value4')]

christophe31