multi dimensional dictionary

Peter Otten __peter__ at web.de
Wed May 28 04:11:19 EDT 2008


Gary Herron wrote:

> Alok Kumar wrote:
>> Dear All,
>>
>> I am using dictionary for filling my xpath parsed data.
>>
>> I wanted to use in the following manner.
>>
>> mydict[index] ["key1"] ["key2"]    #Can someone help me with right
>> declaration.
>>
>> So that I can fill my XML xpath parsed data
>>  
>> mydict[0] ["person"] ["setTime"] = "12:09:30"
>> mydict[0] ["person"] ["clrTime"] = "22:09:30"

[I didn't see the original post]

>>> from collections import defaultdict
>>> def make_inner():
...     return defaultdict(lambda: defaultdict(make_inner))
...
>>> mydict = make_inner()
>>> mydict[0]["person"]["setTime"] = "12:09:30"
>>> mydict[0]["person"]["shoes"]["color"] = "bright yellow"
>>> mydict
defaultdict(<function <lambda> at 0x2b7afd0025f0>, {0: defaultdict(<function
make_inner at 0x2b7afd002578>, {'person': defaultdict(<function <lambda> at
0x2b7afd002668>, {'setTime': '12:09:30', 'shoes': defaultdict(<function
make_inner at 0x2b7afd002578>, {'color': 'bright yellow'})})})})

If that looks too messy, try a subclass:

>>> class Dict(defaultdict):
...     def __init__(self):
...             defaultdict.__init__(self, Dict)
...     def __repr__(self):
...             return dict.__repr__(self)
...
>>> mydict = Dict()
>>> mydict[0]["person"]["setTime"] = "12:09:30"
>>> mydict
{0: {'person': {'setTime': '12:09:30'}}}
>>> mydict[0]["person"]["shoes"]["color"] = "bright yellow"
>>> mydict
{0: {'person': {'setTime': '12:09:30', 'shoes': {'color': 'bright
yellow'}}}}

Peter



More information about the Python-list mailing list