Search code examples
pythondefaultdict

python defaultdict lambda


I'm trying the defaultdict in python. the code is as follows:

dd = defaultdict(lambda :[0,0])
dd[5][4] = 2
print(dd)

But it throws an IndexError

IndexError: list assignment index out of range

and once i change the code to

dd[2][1] = 2

the result is :

defaultdict(<function <lambda> at 0x000001F9F10EE730>, {2: [0, 2]})

I don't know why index out of range and how the range comes.

Thanks!


Solution

  • your defaultdict generates a default entry which has a length of 2.

    When you do dd[5][4] = 2, since key 5 doesn't exist, defaultdict generates a [0,0] value as expected.

    Then you're accessing the 5th index, which is out of range (like you'd do [0,0][4] = 2)

    (of course it works with dd[2][1] = 2 because 1 is within default list range)

    If you don't know the size of your lists and you don't want to know, I suggest to use a default dictionary on a default dictionary of integers, like this:

    dd = defaultdict(lambda : defaultdict(int))
    

    (of course that doesn't generate an array but a dict of dicts, but the dd[5][4] construct works right away)