Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #80177 > unrolled thread
| Started by | Antoon Pardon <antoon.pardon@rece.vub.ac.be> |
|---|---|
| First post | 2014-11-04 14:21 +0100 |
| Last post | 2014-11-04 07:13 -0700 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Dictionaries with variable default. Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2014-11-04 14:21 +0100
Re: Dictionaries with variable default. Cousin Stanley <cousinstanley@gmail.com> - 2014-11-04 07:13 -0700
| From | Antoon Pardon <antoon.pardon@rece.vub.ac.be> |
|---|---|
| Date | 2014-11-04 14:21 +0100 |
| Subject | Re: Dictionaries with variable default. |
| Message-ID | <mailman.15444.1415107297.18130.python-list@python.org> |
Op 03-11-14 om 12:09 schreef Chris Angelico:
> On Mon, Nov 3, 2014 at 10:04 PM, Antoon Pardon
> <antoon.pardon@rece.vub.ac.be> wrote:
>> Is it possible to have a default dictionary where the default is dependant
>> on the key?
>>
>> I was hoping something like this might work:
>>>>> m = defaultdict(lambda key: key+1)
>> But it obviously doesn't:
>>>>> m[3]
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> TypeError: <lambda>() takes exactly 1 argument (0 given)
> Yes, but not with the defaultdict. Instead, just implement __missing__:
>
> class KeyPlusOne(dict):
> def __missing__(self, key): return key+1
>
> ChrisA
So How should I call this:
class ...dict(dict):
def __init__(self, fun):
self.fun = fun
def __missing__(self, key):
return self.fun(key)
[toc] | [next] | [standalone]
| From | Cousin Stanley <cousinstanley@gmail.com> |
|---|---|
| Date | 2014-11-04 07:13 -0700 |
| Message-ID | <m3amur$1d6$1@dont-email.me> |
| In reply to | #80177 |
> So How should I call this:
>
> class ...dict(dict):
> def __init__(self, fun):
> self.fun = fun
>
> def __missing__(self, key):
> return self.fun(key)
I don't know how you should,
but I tried the following
which seems to work ....
class KeyPlusOne( dict ) :
def __missing__( self , key ) :
return ( 2 * key ) + 1
kp1 = KeyPlusOne()
d = { }
for n in range( 11 ) :
d[ n ] = kp1[ n ]
print '\n key : value \n'
for key , value in d.iteritems() :
print ' %2d : %2d' % ( key , value )
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web