Why are there no ordered dictionaries?

Christoph Zwerschke cito at online.de
Sun Nov 20 16:19:55 EST 2005


bonono at gmail.com schrieb:
> By ordered dict, one usually wants order that is arbitary which cannot
> be derived from the content, say insertion order(most ordered dict I
> saw use this order).
> I am writing a web applications(simple forms) which has a number of
> fields. Each field naturally has a name and a number of
> attributes(formatting etc.), like this :
> d = {'a':{...}, 'b':{....}}

Things like that are also my typical use case. The keys usually contain 
things like database fields or html form fields, the values contain the 
corresponding description, formatting, data type or data itself etc.

The example above is a bit misleading, because using 'a', 'b' as keys 
can give the impression that you just have to sort() the keys to have 
what you want. So let's make it more realistic:

d = { 'pid': ('Employee ID', 'int'),
   'name': ('Employee name', 'varchar'),
   'sal': ('Salary', 'float') }

Now if I want these things to be presented in this order, I need to run 
through a separate list ('pid', 'name', 'sal') that holds the order.

Ok, you could simply use a list instead of a dictionary:

d = ( ('pid', 'Employee ID', 'int'),
   ('name', 'Employee name', 'varchar'),
   ('sal', 'Salary', 'float') )

This works as long as you *only* have to go through the list 
sequentially. But maybe you want to print the name with its description 
at some other place as well. Now how do you access its description 
'Employee name' so easily?

-- Christoph



More information about the Python-list mailing list