• Advertisement
Sign in to follow this  

help with python - write class similar to defaultdict

This topic is 1539 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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())

Share this post


Link to post
Share on other sites
Advertisement

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

 

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)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement