Newbie: How to pass a dictionary to a function?

Dan Bishop danb_83 at yahoo.com
Tue Apr 8 06:19:57 CEST 2008


On Apr 7, 10:54 pm, BonusOnus <Bonus.O... at gmail.com> wrote:
> How do I pass a dictionary to a function as an argument?

The same way you pass any other argument.

> # Say I have a function foo...
> def foo (arg=[]):

It's generally a bad idea to use [] as a default argument.

> x = arg['name']
> y = arg['len']
>
> s = len (x)
>
> t = s + y
>
> return (s, t)

Apart from the lack of indentation (and meaningless variable names),
it looks correct.

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

"dict" is a built-in name.  Don't redefine it.

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

Don't redefine "len" or "string" either.

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

Runs fine for me as soon as I fixed the indentation.



More information about the Python-list mailing list