February 18th, 2013, 04:22 PM
Defining Custom Arithmetic Operators For Dictionaries?
So, I run into this problem ALL the time with my dictionary pairs. Here's the simple version:
Whenever I create a dictionary, I don't like to initialize values that I know I won't need. Presently, the generation step is as such:
Often, I only need at most like four of those, although certain exceptions apply.
raw_list = ['$P','CP','PYR','AQA','GEA','AEV','HOL','JNX','PUR','MGC']
for item in raw_list:
self[item] = 0
The work-around that I'm using will probably resemble the one I'm using for yet another dictionary-based class in the program:
Which auto-initializes values that are not yet in the dictionary. It would be much clearer for me if I could, instead of using this method as-written (comp_node.compAdd(it,amt)), have it function as the default += operator for the comp_node class.
if it in self:
self[it] += amt
self[it] = amt
So my questions are as follows:
Is it possible to build custom arithmetic-sign methods ( as explained above) for dictionary objects?
If possible, how can I design new methods for the built-in classes? I really would like such a += operator for all of my dictionaries.
To specify, I'd imagine it behaving as:
comp_node[it] += amt
February 18th, 2013, 06:16 PM
You need a default dictionary.
from collections import defaultdict as cdd
d = cdd(int)
d[tuple] = 24
d[tuple] += 10000
d['blort'] -= 32
[/code] are essential for python code and Makefiles!
February 19th, 2013, 05:18 PM
Yay! It already exists and everything! Thank you so much!
February 19th, 2013, 11:22 PM
For future reference, the way you overload the += operator is by defining a method named __iadd__.