dictionary total sum

Joaquin Alzola Joaquin.Alzola at lebara.com
Wed Sep 7 21:00:59 EDT 2016


On Wednesday, September 7, 2016 at 8:25:42 PM UTC-4, p... at blacktoli.com wrote:
> Hello,
>
> any ideas why this does not work?
>
> >>> def add(key, num):
> ...     a[key] += num
> ...
> >>> a={}
> >>> a["007-12"] = 22 if not a.has_key("007-12") else add("007-12",22)
> >>> a
> {'007-12': 22} # OK here, this is what I want
> >>> a["007-12"] = 22 if not a.has_key("007-12") else add("007-12",22)
> >>> a
> {'007-12': None} # why does this became None?
>
> Thanks

>Your add() function returns None (because it has no return statements).
>Your failing statement is assigning that None to a["007-12"].

>There are a number of helpful structures in Python to do this work for you.  collections.Counter will probably be helpful:

>    >>> from collections import Counter
>    >>> a = Counter()
>    >>> a["007-12"] += 22
>    >>> a
>    Counter({'007-12': 22})
>    >>> a["007-12"] += 22
>    >>> a
>    Counter({'007-12': 44})

Hi Ned

Also:
>>> a={}
>>> a["007-12"]=22
>>> a
{'007-12': 22}
>>> a["007-12"]+=22
>>> a
{'007-12': 44}
>>>

Will this fit his request?
This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.



More information about the Python-list mailing list