Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80151 > unrolled thread

Re: Dictionaries with variable default.

Started byChris Angelico <rosuav@gmail.com>
First post2014-11-03 22:09 +1100
Last post2014-11-03 22:09 +1100
Articles 1 — 1 participant

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.


Contents

  Re: Dictionaries with variable default. Chris Angelico <rosuav@gmail.com> - 2014-11-03 22:09 +1100

#80151 — Re: Dictionaries with variable default.

FromChris Angelico <rosuav@gmail.com>
Date2014-11-03 22:09 +1100
SubjectRe: Dictionaries with variable default.
Message-ID<mailman.15425.1415013405.18130.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web