Saturday, February 12, 2011

Tricky question using Python defaultdict

I got a very interesting question which puzzled me, though I solved it in ten minutes. Its a nice challenge, try to answer the question before you look for the answer. Use python interpreter to try it out.

Collections module in python has a defaultdict(default_factory) which will take in a default value and return it if we try to access the key which is not there. In the case of normal dictionary, we will get a key error.

>> d = dict()
>>d['rr']
KeyError: 1

>> from collections import defaultdict
>> dd= defaultdict(int)
>>dd['rr']
0

But now if you try to access this, we get
>>dd['rr']['tt']
TypeError: 'int' object is unsubscriptable

Now, here is the question. How will you make it work? Also you need to access arbitrary number of dictionary of dictionaries (for example >>dd['rr']['tt']['t'] =1), write a function to make this possible.

No comments: