- Python Home
- About
- News
- Documentation
- Downloads
- Community
- Foundation
- Developer's Guide
- Issue Tracker
- Issues
- Summaries
- User
- Administration
- Help
Issue19427
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.
Created on 2013-10-28 23:16 by Richard.Neill, last changed 2022-04-11 14:57 by admin. This issue is now closed.
| Messages (4) | |||
|---|---|---|---|
| msg201587 - (view) | Author: Richard Neill (Richard.Neill) | Date: 2013-10-28 23:16 | |
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.
|
|||
| msg201588 - (view) | Author: Eric V. Smith (eric.smith) * ![]() |
Date: 2013-10-28 23:21 | |
I suggest you get consensus on this idea on the python-ideas mailing list first. |
|||
| msg201606 - (view) | Author: R. David Murray (r.david.murray) * ![]() |
Date: 2013-10-29 06:46 | |
In the meantime the issue should be closed. It can be reopened if consensus is reached. |
|||
| msg201607 - (view) | Author: Georg Brandl (georg.brandl) * ![]() |
Date: 2013-10-29 06:57 | |
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. |
|||
| History | |||
|---|---|---|---|
| Date | User | Action | Args |
| 2022-04-11 14:57:52 | admin | set | github: 63626 |
| 2013-10-29 06:57:41 | georg.brandl | set | nosy:
+ georg.brandl messages: + msg201607 |
| 2013-10-29 06:46:15 | r.david.murray | set | status: open -> closed nosy: + r.david.murray messages: + msg201606 resolution: postponed stage: resolved |
| 2013-10-28 23:21:43 | eric.smith | set | nosy:
+ eric.smith messages: + msg201588 |
| 2013-10-28 23:16:08 | Richard.Neill | create | |


