471,330 Members | 1,053 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

Function return a dictionary

Hi all,

I'm doing a function which needs return an arrary -- or more specially a
dictionary data type.
I have a sample like this

def AFC():
v["a"] = 1
return v

v = AFC()
print v["a"]

with error
NameError: global name 'v' is not defined

how do I go about it?

Thanks in advance.
Boris Mok
Oct 1 '07 #1
2 28849
Boris Mok <bo******@iwow.com.sgwrites:
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
Oct 1 '07 #2
Boris Mok <bo******@iwow.com.sgwrote:
Hi all,

I'm doing a function which needs return an arrary -- or more specially a
dictionary data type.
I have a sample like this

def AFC():
v["a"] = 1
return v

v = AFC()
print v["a"]

with error
NameError: global name 'v' is not defined

how do I go about it?
At some point you have to initialise v to a dictionary, Python isn't going
to guess for you. e.g.

def AFC():
v = {}
v["a"] = 1
return v
Oct 1 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by david | last post: by
4 posts views Thread by wongjoekmeu | last post: by
8 posts views Thread by Ravindranath Gummadidala | last post: by
7 posts views Thread by chellappa | last post: by
6 posts views Thread by John | last post: by
4 posts views Thread by barcaroller | last post: by
10 posts views Thread by AlFire | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.