Function return a dictionary

B

Boris Mok

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
 
B

Ben Finney

Boris Mok said:
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.
 
D

Duncan Booth

Boris Mok said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top