Function return a dictionary

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Oct 1 03:56:39 EDT 2007


Boris Mok <borismok at iwow.com.sg> writes:

> I'm doing a function which needs return an arrary -- or more specially
> a dictionary data type.

Yes. Python doesn't have an "array" type natively, and it's confusing
to refer to a dict as an array because there *are* "array"s in PyNum.

> I have a sample like this
> 
> def AFC():
>  v["a"] = 1
>  return v

Your function never specifies where 'v' comes from. So, when you first
attempt to access an item from 'v' as an existing dict, you get a
NameError.

If you want to create 'v' inside the function, you'll need to do so
before attempting to use it.

    def foo():
        bar = {"spam": 1}
        return bar

    cheeseburger = foo()
    print cheeseburger["spam"]

To get a thorough grounding in basic concepts like this, please work
through the Python tutorial <URL:http://docs.python.org/tut/>, from
beginning to end, running every example and experimenting until you
understand why it does what it does, before moving onto the next.

-- 
 \     "[T]he question of whether machines can think [...] is about as |
  `\         relevant as the question of whether submarines can swim." |
_o__)                                            —Edsger W. Dijkstra |
Ben Finney



More information about the Python-list mailing list