Jump to content

View more

Image of the Day

Boxes as reward for our ranking mode. ヾ(☆▽☆)
#indiedev #gamedev #gameart #screenshotsaturday https://t.co/ALF1InmM7K
IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.


Sign up now

help with python - write class similar to defaultdict

4: Adsense

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   

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


#2 swiftcoder   Senior Moderators   

18212
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] [GitHub]





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.