unicornication
unicornication

Reputation: 627

Overloading operators with dictionaries in Python

I have a class L that takes multiple dictionaries like this:

L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'))

I'm trying to add two D objects together and return a new L object, such that

a = L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'))
b = L((n:'morapple', t:'23', f:'44'),(m:'14', n:'132', p:'morecats'))
>> a+b
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'),(n:'morapple', t:'23', f:'44'),(m:'14', n:'132', p:'morecats'))
c = (c:'carrot',d:'2')
>>a+c
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'),(c:'carrot',d:'2'))

I'm really lost, so far I've tried to use eval() with no success.. it returns nothing and I'm not sure what to do?

Upvotes: 0

Views: 907

Answers (1)

Raniz
Raniz

Reputation: 11113

First off, stay away from eval() it is very, very seldom a good idea to use it.

Secondly, why can't you just do this:

def __add__(self, other):
    if type(other) == dict:
       return DL(*(self.dicts + [other]))
    elif type(other) == DL:
       return DL(*(self.dicts + other.dicts))
    raise ValueError("Only DL and dict are supported")

Upvotes: 3

Related Questions