0

I would like to write the + operator for dictionaries.

I know a similar question has been asked before like here, but I would like to write the + operator for a dictionary instead.

I know that it is possible to overload an operator in a custom class in Python. However I did not find how to overload an operator in a built-in class (if that is actually possible). Also since the + operator is not defined for a dictionary in Python I wonder if that is possible at all?

I think this question has not been asked before on SO since I could not find something like it. Perhaps I just did not find the right terms to search for it. Another link that might be useful for that question.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nils
  • 910
  • 8
  • 30
  • No, but yes, check this example: https://stackoverflow.com/questions/6738987/extension-method-for-python-built-in-types – kederrac Aug 23 '19 at 08:29

1 Answers1

0

I guess what you want to do is implement add method to dictionaries - You might want to use your own logic, I am here using update method to add. You will have to inherit and overload the add method to make this happen. Here is how to do it.

class dicti(dict):
    def __add__(self, obj):
        temp = {}
        temp.update(self)
        temp.update(obj)
        return temp
a = dicti({'a':1,'b':2})
b = dicti({'c':2})
c = a+b
print(a) #outputs -> {'a': 1, 'b': 2}
print(b) #outputs -> {'c':2}
print(c) #outputs -> {'a': 1, 'b': 2, 'c': 2}
Abhijeetk431
  • 847
  • 1
  • 8
  • 18