views:

584

answers:

3

Hi, new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.

So if I have the dictionary:

d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}

It isn't in that order if I view it or iterate through it, is there any way to make sure Python will keep the explicit order that I declared the keys/values in?

Using Python 2.6

+9  A: 

You need an ordered dictionary, you can find an example of one here

Mark Roddy
You can also upgrade to python 2.7 when it comes out, the OrderedDict class is being added as a part of PEP 372 http://docs.python.org/dev/whatsnew/2.7.html
Dana the Sane
A: 

Dictionaries will use an order that makes searching efficient, and you cant change that,

You could just use a list of objects (a 2 element tuple in a simple case, or even a class), and append items to the end. You can then use linear search to find items in it.

Alternatively you could create or use a different data structure created with the intention of maintaining order.

Fire Lancer
A: 

Generally, you can design a class that behaves like a dictionary, mainly be implementing the methods __contains__, __getitem__, __delitem__, __setitem__ and some more. That class can have any behaviour you like, for example prividing a sorted iterator over the keys ...

Rasmus Kaj