The value assigned to a key in a dictionary can itself be another dictionary
creatures = dict() creatures['birds'] = dict() creatures['birds']['eagle'] = dict() creatures['birds']['eagle']['female'] = 0 creatures['birds']['eagle']['female'] += 1
However, you need to explicitly create each dictionary. Unlike Perl, Python does not automatically create a dictionary when you try to process the value of an unassigned key as such.
Unless, of course, you are using defaultdict :
from collections import defaultdict creatures = defaultdict( lambda: defaultdict(lambda: defaultdict( int ))) creatures['birds']['eagle']['female'] += 1
For arbitrary nesting levels, you can use this recursive definition.
dd = defaultdict( lambda: dd ) creatures = dd creatures['birds']['eagle']['female'] = 0
In this case, you need to explicitly initialize the integer value, since otherwise the value of creatures['birds']['eagle']['female'] will be considered another defaultdict :
>>> creatures = dd >>> type(creatures['birds']['eagle']['female']) <class 'collections.defaultdict'>
source share