help with python - write class similar to defaultdict

Started by
0 comments, last by swiftcoder 10 years, 5 months ago

http://docs.python.org/2/library/collections.html#collections.defaultdict

Hi, I am new to python and trying to write a class similar to to the defaultdict class.

I am little stuck on the constructor. On the python website example they first create a the defaultdict object with type as parameter, and then fill it. Example d = defaultdict(list) and then input "key,value"

If I directly pass "s" when creating object, it seems to be fine, but how can I make it similar to how it's really implemented. Thanks for help!


class MyDictionary(dict): #Parent class is "dict"
    'This is a derived class from python dict'
 
    def __init__(self, default_factory=None): # implement the parameters correctly
        dict.__init__(self, default_factory)
        #self.default_factory = default_factory
 
    #def anotherMethod-ToDo-forexmaple-d[10],handle if key doesn't exist
        
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = MyDictionary(list)
 
for k, v in s:
    d[k].append(v)
    
print (d.items())
Advertisement

I think the functionality you are looking for is 'named arguments' (also referred to as **kwargs).

Python functions may declare an optional parameter prefixed by a double-asterix. The value of this parameter will be a dictionary containing all the named arguments specified for the function.

See the following example:


def my_function(**kwargs):
    print kwargs
 
my_function(animal='cat', size='small', intelligence='high', lives=9)

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement