Why are there no ordered dictionaries?

Fredrik Lundh fredrik at pythonware.com
Sun Nov 20 16:45:22 EST 2005


Christoph Zwerschke wrote:

> 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') )

if you restructure the list somewhat

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

you can still loop over the list

    for key, (name, type) in d:
        print key, name, type # e.g. generate form entry

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

but you can easily generate an index when you need it:

    index = dict(d)

    name, type = index["pid"]
    print name

the index should take less than a microsecond to create, and since it
points to the members of the original dict, it doesn't use much memory
either...

</F>






More information about the Python-list mailing list