sorting tuples...

Dan Sommers me at privacy.net
Wed Sep 28 04:50:42 CEST 2005


On 27 Sep 2005 19:01:38 -0700,
nidhog at gmail.com wrote:

> with the binary stuff out of the way, what i have is this string data:

> 20050922 # date line
> mike
> mike's message...
> 20040825 # date line
> jeremy
> jeremy's message...
> ...

> what i want to do is to use the date line as the first data in a tuple
> and the succeeding lines goes into the tuple, like:

> (20050922, mike, mike's message)

> then when it matches another date line it makes another new tuple with
> that date line as the header data and the succeeding data, etc..

> (20050922, mike, mike's message)
> (20040825, jeremy, jeremy's message)
> ...

> then i would sort the tuples according to the date.

> is there an easier/proper way of doing this without generating alot of
> tuples?

You want a dictionary.  Python dictionaries map keys to values (in other
languages, these data structures are known as hashes, maps, or
associative arrays).  The keys will be the dates; the values will depend
on whether or not you have multiple messages for one date.

If the dates are unique (which, looking at your data, is probably not
true), then each item in the dictionary can be just one (who, message)
tuple.

If the dates are not unique, then you'll have to manage each item of the
dictionary as a list of (who, message) tuples.

And before you ask:  no, dictionaries are *not* sorted; you'll have to
sort a separate list of the keys or the items at the appropriate time.

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list