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

David Rock david at graniteweb.com
Tue Mar 6 19:19:10 CET 2012


* Abhishek Pratap <abhishek.vit at gmail.com> [2012-03-06 09:50]:
> Hi Guys
> 
> 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"}
> 
> Can I do something similar with dictionaries in Python.

Absolutely.  Python is very good at using nested dicts.

dict = {}
dict['a'] ={} 
dict['a']['b'] = {}
dict['a']['b']['c']= "value"


This is a bit brute force, but it illustrates that the intermediary keys
need to exist.  ie, if you try to assign directly, it won't work:

Type "help", "copyright", "credits" or "license" for more information.
>>> dict ={}
>>> dict['a']['b']['c'] = 'value'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  KeyError: 'a'

Since the key 'a' doesn't exist, it throws an exception.

Python is also more flexible than perl in nesting data because it
doesn't have to be the same data type.  You can nest variables, lists,
dicts, etc all at the same level:

dict = {}
dict['mylist'] = [1,2,3]
dict['mystring'] = 'string'
dict['mynum'] = 4
dict['anotherdict'] = {}
dict['anotherdict']['anotherstring'] = 'string2'

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120306/62458b93/attachment-0001.pgp>


More information about the Tutor mailing list