You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Activity
RichardNeill commentedon Oct 28, 2013
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:
Perhaps this might need an "import dictionarymath" to enable the behaviour.
Thanks for your consideration of my idea.
ericvsmith commentedon Oct 28, 2013
I suggest you get consensus on this idea on the python-ideas mailing list first.
bitdancer commentedon Oct 29, 2013
In the meantime the issue should be closed. It can be reopened if consensus is reached.
birkenfeld commentedon Oct 29, 2013
This specialized use case has no chance of being added to the very general dict object.
But have a look at the collections.Counter class which does exactly what you propose for positive values and the +/- operations.