Newbie: How to pass a dictionary to a function?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue Apr 8 01:12:01 EDT 2008
En Tue, 08 Apr 2008 00:54:09 -0300, BonusOnus <Bonus.Onus at gmail.com>
escribió:
> How do I pass a dictionary to a function as an argument?
The indentation is lost, so it's not easy to check your program.
> # Say I have a function foo...
Original: def foo(arg=[]). An empty list isn't a good default value here,
perhaps you intended to use {}? Anyway, don't use mutable default values;
see this FAQ entry:
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
def foo(arg):
x = arg['name']
y = arg['len']
s = len(x)
t = s + y
return s, t
# don't use dict as a variable name, you're hiding the builtin dict type
my_dict = {}
my_dict['name'] = 'Joe Shmoe'
my_dict['len'] = 44
# don't use len as a name either
# nor string!
length, string = foo(my_dict)
> # This bombs with 'TypeError: unpack non-sequence'
> What am I doing wrong with the dictionary?
Nothing. Written as above, it works fine. Don't retype your programs,
always copy & paste from the same source you're executing. If you get an
exception, post the entire traceback with the exact exception name and
message.
--
Gabriel Genellina
More information about the Python-list
mailing list