Newbie: How to pass a dictionary to a function?

Matt Nordhoff mnordhoff at mattnordhoff.com
Tue Apr 8 00:11:10 EDT 2008


BonusOnus wrote:
> How do I pass a dictionary to a function as an argument?
> 
> 
> # Say I have a function foo...
> def foo (arg=[]):
> x = arg['name']
> y = arg['len']
> 
> s = len (x)
> 
> t = s + y
> 
> return (s, t)

I assume you actually indented the body of the function?

> # The dictionary:
> 
> dict = {}
> dict['name'] = 'Joe Shmoe'
> dict['len'] = 44

'dict' is the name of a built-in type. You should name your variable
something else.

> # I try to pass the dictionary as an argument to a
> # function
> 
> len, string = foo (dict)

'len' is the name of a built-in function and 'string' is a module in the
standard library. You should name both of them something else.

> # This bombs with 'TypeError: unpack non-sequence'
> 
> What am I doing wrong with the dictionary?

It would be helpful to provide the full traceback, since that says what
line the problem is on...

HTH (it probably won't)
-- 



More information about the Python-list mailing list