[Tutor] Circular approach to a dictionary structure

Andrei project5 at redrival.net
Sat Oct 29 01:32:42 CEST 2005


Tim Johnson wrote:
> Hello:
> 
> # I have the following dictionary:
> next_phases = {"open":"review","review":"write","write":"open"}
> 
> # a 'phase is extracted by
> next_phase = next_phases[self.phase
> 
> Note that the value for each of the first keys is the key for
> the next item, and that the value for the last key is the *first* key.

I too would be tempted to use a list for this. Something along the lines of:

   phases = ['open', 'review', 'write']

   nextphase = phases[((1 + phases.index(phase)) % len(phases)]

This is not as friendly as the dictionary option, but I'd wrap that in a 
function call (or object interface). It has some advantages:
   - there's a single instance of every string
   - it's obvious that it's a sequence
   - it's one of the standard ways of doing circular structures
   - there's no chance of introducing a dead branch, breaking the circle
   - it's easier to add/remove things.
     E.g. if you'd add and an "approve" step between review and write,
     the list approach requires a single update, while the dictionary
     requires one new key-value pair and modifications in another two
     places in order to get it working correctly.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])



More information about the Tutor mailing list