A question of style (finding item in list of tuples)

Tim Chase python.list at tim.thechases.com
Mon May 21 09:34:11 EDT 2012


On 05/21/12 08:10, Steven D'Aprano wrote:
> On Mon, 21 May 2012 08:37:29 -0400, Roy Smith wrote:
> 
> [...]
>> The above code works, but it occurs to me that I could use the much
>> shorter:
>>
>>     def experience_text(self):
>>         return dict(CHOICES).get("self.level", "???")
>>
>> So, the question is, purely as a matter of readability, which would you
>> find easier to understand when reading some new code?
> 
> Definitely the dictionary lookup.
> 
> Rather than convert list CHOICES to a dict every time, you might convert 
> it to a dict *once*, then just write:
> 
> return CHOICES.get(self.level, "???")

While I back Steven's suggestion, I'd keep *both* around.  The
dictionary isn't inherently ordered, so presenting it to the user
may come out with a differing orders depending on how code gets hit.
 So I'd do

  CHOICES = [
    ("NONE", "No experience required"),
    ...
    ]
  CHOICE_DICT = dict(CHOICES)

once at setup, and then use Steven's suggestion of

  return CHOICES_DICT.get(self.level, "???")

then you get the best of both worlds:  You can specify the order for
presentation using CHOICES, and get O(1) lookups and defaulting via
CHOICE_DICT.

-tkc






More information about the Python-list mailing list