This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Richard.Neill
Recipients Richard.Neill
Date 2013-10-28.23:16:08
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1383002168.86.0.538679547353.issue19427@psf.upfronthosting.co.za>
In-reply-to
Content
It would be really nice if python supported mathematical operations on dictionaries. This is widely requested (eg lots of stackoverflow queries), but there's currently no simple way to do it.

I propose that this should work in the "obvious" way, i.e. for every key in common between the dicts, apply the operator to the set of values.  If the dicts have some keys that are not in common, then create the missing keys, with a value of zero (which does sensible things for +,-,* and will throw an error if missing element is a divisor). 

It should also allow a dict to be added/multiplied etc with a scalar.

If the dict contains anything other than key:value pairs (i.e. the values are non-scalar types), then this should throw an error.

For example:

>>> d1 = { 'a':1, 'b':2, 'c':3}
>>> d2 = { 'a':4, 'b':5, 'c':6}
>>> d3 = d1 + d2
>>> d3
{'a': 5, 'b': 7, 'c': 9}

>>> d4 = d1 + 17
>>> d4 
{'a': 18, 'b': 19, 'c': 20}

>>> d5 = { 'a':4, 'b':5, 'x':6}
>>> d6 = d1 + d5
>>> d6
{'a': 5, 'b': 7, 'c': 3, 'x': 6}

Perhaps this might need an "import dictionarymath" to enable the behaviour.

Thanks for your consideration of my idea.
History
Date User Action Args
2013-10-28 23:16:08Richard.Neillsetrecipients: + Richard.Neill
2013-10-28 23:16:08Richard.Neillsetmessageid: <1383002168.86.0.538679547353.issue19427@psf.upfronthosting.co.za>
2013-10-28 23:16:08Richard.Neilllinkissue19427 messages
2013-10-28 23:16:08Richard.Neillcreate