#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2

    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:

    Code:
    class pouch(dict):
    raw_list = ['$P','CP','PYR','AQA','GEA','AEV','HOL','JNX','PUR','MGC']
    
    	def __init__(self):
    		for item in raw_list:
    			self[item] = 0
    Often, I only need at most like four of those, although certain exceptions apply.
    The work-around that I'm using will probably resemble the one I'm using for yet another dictionary-based class in the program:

    Code:
    class comp_node(node,dict):
    	def compAdd(self,it,amt):
    		if it in self:
    			self[it] += amt
    		else:
    			self[it] = amt
    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.
    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
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,703
    Rep Power
    480
    You need a default dictionary.
    Code:
    from collections import defaultdict as cdd
    
    d = cdd(int)
    
    d[tuple] = 24
    d[tuple] += 10000
    d['blort'] -= 32
    print(d)
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Yay! It already exists and everything! Thank you so much!
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    For future reference, the way you overload the += operator is by defining a method named __iadd__.

IMN logo majestic logo threadwatch logo seochat tools logo