* Abhishek Pratap <abhishek....@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
da...@graniteweb.com

Attachment: pgp8ik0yrru5G.pgp
Description: PGP signature

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to