Returning dictionary from a function

John Machin sjmachin at lexicon.net
Thu May 14 18:24:52 EDT 2009


On May 15, 7:38 am, kk <maymunbe... at gmail.com> wrote:
> Hi
>
> I am working on something here and I cannot get the full dictionary
> out of a function. I am sure I am missing something here.
>
> Anyways here is a simple code that repeats my problem. Basically I am
> just trying to get that values function to return the diky as a
> dictionary so that I can query values later.
>
> thanks
>
> def values(x):
>     diky={}
>     for a in range(x):
>         a=a+100

And you have a SECOND problem ... rebinding your loop counter is
likely to confuse anybody (including yourself!) who tries to
understand (let alone maintain!) your code. If you want a to have
values 0, 100, 200, 300, 400 as the loop is traversed, you should use

   for a in range(0, 500, 100):

or maybe you want 100, ...., 104 which would be produced by
EITHER
   for a in range(100, 105):
OR
   for c in range(5):
       a = c + 100

>         diky={chr(a):a}

Note that chr(a) will cause an exception when a >= 256 ... do you need
unichr()?

AND what is the point of this dicky diky anyway? Have you considered
the ord() function?

>
>         print diky
>     return diky
>
> b=values(5)
> print type(b),len(b), b['f'] # gives error
> print type(b),len(b), b['h'] # does not give error

As expected; the last value of a was 104 and ord('h') == 104 ...

HTH,
John



More information about the Python-list mailing list