Dynamic Dictionary Creation
Bob van der Poel
bvdpoel at kootenay.com
Fri Dec 6 18:00:59 EST 2002
Skip Montanaro wrote:
>
> Instead of
>
> def getNoteLen(x):
> global TicksQ
> ntb = { '1': TicksQ * 4,
> '2': TicksQ * 2,
> '4': TicksQ,
> '8': TicksQ
> }
> return ntb[str(x)]
>
> try this:
>
> ntb = { '1': TicksQ * 4,
> '2': TicksQ * 2,
> '4': TicksQ,
> '8': TicksQ
> }
> def getNoteLen(x):
> return ntb[str(x)]
>
> or if you want the avoid the global lookup of ntb:
>
> def getNoteLen(x,ntb=ntb):
> return ntb[str(x)]
>
> It will get done once, then not repeated. When the function is called it
> will always be a local.
>
> Also, note that you don't need to use a global statement to read global
> variables, only to modify them.
Thanks, Skip, for the suggestion. Guess I should have been a bit more
clear, but
the reason for sticking the table inside the function was to hide the
table name. Not a big deal to define it 'globally'.
Is there a reason for the ntb=ntb in your function declaration? If the
table is external to the function, would:
def getNoteLen(x):
return ntb[str(x)]
be the same?
Also, to another poster whose message I lost (sorry), the reason for the
table is that there is not a 1 to 1 relationship which can be simple to
calculate. As mentioned in the original post, the example is
abbreviated.
Guess another solution would be to have this all wrapped in a class.
--
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bvdpoel at kootenay.com
WWW: http://www.kootenay.com/~bvdpoel
More information about the Python-list
mailing list