dictionary of dictionaries

Kay Schluehr kay.schluehr at gmx.net
Tue Dec 11 04:26:36 EST 2007


On Dec 9, 9:35 am, kettle <Josef.Robert.No... at gmail.com> wrote:
> Hi,
>  I'm wondering what the best practice is for creating an extensible
> dictionary-of-dictionaries in python?
>
>  In perl I would just do something like:
>
> my %hash_of_hashes;
> for(my $i=0;$i<10;$i++){
>     for(my $j=0;$j<10;$j++){
>         ${$hash_of_hashes{$i}}{$j} = int(rand(10));
>     }
>
> }
>
> but it seems to be more hassle to replicate this in python.  I've
> found a couple of references around the web but they seem cumbersome.
> I'd like something compact.
> -joe

You might produce the behaviour of the hash_of_hashes type directly:

class dict_of_dicts(dict):
    def __getitem__(self, key):
        d = dict.get(self, key, {})
        self[key] = d
        return d

    def __setitem__(self, key, val):
        assert isinstance(val, dict), "Value of type dict expected. %s
found instead."%(type(val))
        dict.__setitem__(self, key, val)


>>> d = dict_of_dicts()
>>> d[0][1] = "A"
>>> d[1][1] = "B"
>>> d[1][2] = "C"
>>> d
{0: {1: 'A'}, 1: {1: 'B', 2: 'C'}}
>>> d[0] = 0  # expects values of type dict
Traceback
...
AssertionError: Value of type dict expected. <type 'int'> found
instead.



More information about the Python-list mailing list