Having problems accepting parameters to a function
7stud
bbxx789_05ss at yahoo.com
Tue May 1 13:06:23 EDT 2007
On May 1, 10:38 am, rh0dium <steven.kl... at gmail.com> wrote:
> Hi Experts!!
>
> I am trying to get the following little snippet to push my data to the
> function func(). What I would expect to happen is it to print out the
> contents of a and loglevel. But it's not working. Can someone please
> help me out.
>
> ---------<snip>--------------
> #!/usr/bin/env python
>
> import random
>
> def func(*args, **kwargs):
> print kwargs.get('a', "NOPE")
> print kwargs.get('loglevel', "NO WAY")
>
> def main():
> b = []
> for x in range(5):
> b.append({'a':random.random(), "loglevel":10})
>
> for y in b:
> apply(func,y)
>
> # First attempt - didn't work
> # for y in b:
> # func(y)
>
> if __name__ == '__main__':
> main()
1) apply() is deprecated
2) You need to unpack the dictionary using ** before sending it to
func(), whereupon it will be repacked into a dictionary.
import random
def func(*args, **kwargs):
print kwargs.get('a', "NOPE")
print kwargs.get('loglevel', "NO WAY")
def main():
b = []
for x in range(5):
b.append({'a':random.random(), "loglevel":10})
for y in b:
func(**y)
if __name__ == '__main__':
main()
You might consider redefining func() so that you don't have to do the
unpack--repack:
More information about the Python-list
mailing list