question about dictionary type..
Carl Banks
imbosol at vt.edu
Fri Sep 13 14:13:38 EDT 2002
eugene kim wrote:
> hi..
>
> i'd like to have a dictionary which looks like
> table = { category1 : { category2 : { category3 : 'garbage value' } } }
>
> category1 has many category2
> category2 has many category3
>
> i expected
> table[ 'computer' ][ 'language' ][ 'python' ] = 0
> to create {computer : { language : { python :0 }}}
> table[ 'computer' ][ 'language' ][ 'java' ] = 0
> to becomes { 'computer' : { 'language' : { 'python' :0 , 'java' :0 }}}
>
> but python doesn't allow me to do this..
> can anyone help me?
Yes. Python is not Perl. It does not automatically create
dictionaries or lists; you have to create the dict or list and bind it
to something first. In other words, you can't do this:
a['b'] = c
so ou have to do this:
a = {}
a['b'] = c
========
However, I thought it might be useful initialize deeply-nested tables
without having to explicitly create each new dictionary, so I thought
I'd program something up that does that (requires Python 2.2, of
course):
class autonestdict(dict):
def __getitem__(self,attr):
try:
return super(autonestdict,self).__getitem__(attr)
except KeyError:
return _autonestclosure(self,attr)
class _autonestclosure(object):
def __init__(self,nest,attr):
self.nest = nest
self.attr = attr
def __getitem__(self,attr):
return _autonestclosure(self,attr)
def __setitem__(self,attr,value):
obj = autonestdict()
obj[attr] = value
self.nest[self.attr] = obj
Then, you can use it like this:
table = autonestdict()
table[ 'computer' ][ 'language' ][ 'python' ] = 0
table[ 'computer' ][ 'language' ][ 'java' ] = 1
The big problem with this class is when you do something like this:
result = table['computador']
You don't get a KeyError; instead result gets bound to a
_autonestclosure object. Which makes detecting errors kind of hard.
--
CARL BANKS
http://www.aerojockey.com
More information about the Python-list
mailing list