Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!


1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


help with python - write class similar to defaultdict


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 musafir2007   Members   -  Reputation: 201

Like
1Likes
Like

Posted 31 October 2013 - 02:17 PM

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


Sponsor:

#2 swiftcoder   Senior Moderators   -  Reputation: 11763

Like
0Likes
Like

Posted 01 November 2013 - 08:42 AM

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 - Software Engineer @Amazon - [swiftcoding]





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS