[Tutor] creating dict of dict : similar to perl hash of hash

Martin A. Brown martin at linux-ip.net
Tue Mar 6 19:18:43 CET 2012


Hello there Abhi,

 : I am looking for a way to build dictionaries of dict in python.
 : 
 : For example in perl I could do
 : 
 : my $hash_ref = {};
 : $hash->{$a}->{$b}->{$c} = "value";
 : if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"}

Autovivifying.  That's what the perl-heads call that.

 : Can I do something similar with dictionaries in Python.

I suspect you want to look into the collections module.  Here's an 
example of how to use it to create a two-level dictionary with the 
same autovivifying behaviour you are accustomed to in perl.

  >>> import collections
  >>> d = collections.defaultdict(collections.defaultdict)
  >>> a,b,c = range(3)
  >>> d[a][b] = c
  >>> d
  defaultdict(<type 'collections.defaultdict'>, {0: defaultdict(None, {1: 2})})

Have a look at the collections module.  See if that scratches your 
itch.

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list