a question about map object

Alex Martelli aleax at aleax.it
Mon Mar 17 02:50:50 EST 2003


Frank Zheng wrote:
   ...
> i think the map is a ordered-sequences, 

No, one crucial characteristic of Python's dictionaries is that they
give NO guarantee on key ordering -- that's a key part of how dicts
manage to be SO blazingly fast.

> but what should i do can keep its order be same with
> input order

Once you start with dict literal syntax, "{key:value, ..", it's
too late to do anything regarding "input order" -- that "order" is
not recorded anywhere.

If key order is important to you, then you need to maintain a
list of keys that is separate from the dict object itself.  So,
in particular, your literal syntax should be a tuple of tuples:

toft = ( (key, value),
         # etc, etc
       )

and you can form the dict object by calling dict(toft) and
keep both the dict object and the tuple of tuples around and
in sync with each other.


Alex





More information about the Python-list mailing list