Advanced Dictionary
Ian Kelly
ian.g.kelly at gmail.com
Wed Jun 16 11:16:24 EDT 2010
On Wed, Jun 16, 2010 at 4:43 AM, Thomas Lehmann <t.lehmann at rtsgroup.net> wrote:
> Hi,
>
> I have seen a recipe which allows auto creation of missing values for
> dictionaries.
> However this recipe is not working for all.
>
> class AutoValueDict(dict):
> def __makeitem__(self, key):
> return self.setdefault(key, {})
>
> def __getitem__(self, key):
> return self.get(key, self.__makeitem__(key))
>
> I would like to have a dictionary which ensures dictionaries as values
> except when I'm assigning another:
>
> dict["abc"]["xyz"]["123"]["456"] = 123
>
> How can I do this without many "if" and "else"?
Why not use defaultdict?
from collections import defaultdict
def recursive_defaultdict():
return defaultdict(recursive_defaultdict)
my_dict = recursive_defaultdict()
my_dict["abc"]["xyz"]["123"]["456"] = 123
Cheers,
Ian
More information about the Python-list
mailing list