[Tutor] creating a nested dictionary
Kent Johnson
kent37 at tds.net
Fri Feb 1 04:22:19 CET 2008
Ricardo Aráoz wrote:
> These solutions sometimes may have unexpected behavior.
> class recursivedefaultdict(defaultdict):
> def __init__(self):
> self.default_factory = type(self)
> d = recursivedefaultdict()
> d['pepe']['jose']['juan'] = 25
> d['pepe']['jose'] = 25
Presumably you mean
d['pepe']['martin'] = 25
> [i for i in d['pepe']]
> it prints : ['jose', 'pedro', 'martin']
> expected : [defaultdict(<class '__main__.hash'>, {'jose':
> defaultdict(<class '__main__.hash'>, {'juan': 25}), 'pedro': 25,
> 'martin': 33})]
I think your expectations are off. Iterating a dict gives the keys:
In [14]: d=dict(juan=25, pedro=25, martin=33)
In [15]: d
Out[15]: {'juan': 25, 'martin': 33, 'pedro': 25}
In [16]: [ i for i in d]
Out[16]: ['juan', 'pedro', 'martin']
Kent
More information about the Tutor
mailing list