Skip to content Skip to sidebar Skip to footer

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()):

Solution 1:

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 

Solution 2:

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

Solution 3:

Short answer: no. Python dictionaries are fundamentally unordered.

Post a Comment for "Ordering In Python (2.4) Dictionary"