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

Thomas Maier hayzer at gmail.com
Tue Mar 6 23:38:11 CET 2012


On Tue, Mar 6, 2012 at 8:19 PM, David Rock <david at graniteweb.com> wrote:
> * 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'
>
Hi David,
Mixed data types in nested data structure are possible in Perl as well:
%hash = ();
$hash{'mylist'} = [1,2,3];
$hash{'mystring'} = 'string';
$hash{'mynum'} = 4;
$hash{'anotherhash'} = {};
$hash{'anotherhash'}{'anotherstring'} = 'string2';

Thomas


More information about the Tutor mailing list