how best to use a dictionary in this function?

Aaron "Castironpi" Brady castironpi at gmail.com
Thu Oct 2 05:22:07 EDT 2008


On Oct 2, 4:18 am, Terrence Brannon <metap... at gmail.com> wrote:
> Ok, here is some code:
>
> def calc_profit(std_clicks, vip_clicks, ad_rate=200,
> upline_status=None):
>     payout = {}
>     payout_std = std_clicks * rates['std'].per_click
>     payout_vip = vip_clicks * rates['vip'].per_click
>
> ... now note that std_clicks and vip_clicks are passed to the
> function.
>
> Now, I improved this function this way:
>
> def calc_profit(std_clicks, vip_clicks, ad_rate=200,
> upline_status=None):
>     clicks = {}
>     clicks['std'] = std_clicks
>     clicks['vip'] = vip_clicks
>
>     payout = {}
>     for member_type in rates:
>         payout[member_type] = clicks[member_type] *
> rates[member_type].per_click
>
> But it seems wasteful to have to re-bind the passed-in function args
> to a dictionary in the function. I think there must be some way to
> improve this code and get the dictionary built without me manually
> doing it...
>
> I know there is something like *args, or **args, but since
> docs.python.org is down, I cant check.

*args is for variable-length parameters, **args is for keyword
parameters.

>>> def f( **kwar ):
...     print kwar
...
>>> f( a=2, b=3 )
{'a': 2, 'b': 3}
>>> f( 123 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 0 arguments (1 given)
>>> f( a='abc' )
{'a': 'abc'}



More information about the Python-list mailing list