question about dictionary type..

Frank Buss fb at frank-buss.de
Sat Sep 14 06:58:33 EDT 2002


eugene kim <eugene1977 at hotmail.com> wrote:

> 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 }}}

If you don't insist on your syntax, a little function is all you need:

def add(tree, path, value):
  start=tree
  for key in path[:-1]:
    if start.has_key(key):
      start = start[key]
    else:
      start[key] = start = {}
  start[path[-1]] = value

You can use it like this, with tuples and lists:

>>> tree={}
>>> add(tree, ('computer', 'language', 'python'), 'cool!')
>>> add(tree, ['computer', 'language', 'java'], 'cumbersome')
>>> tree
{'computer': {'language': {'python': 'cool!', 'java': 'cumbersome'}}}

Interesting is the line "start[key] = start = {}", because first
"start[key] = {}" is evaluated, then "start = {}" (with "{}" being the 
same object as in the first assignment). You can check this with "dis", as 
I've read in another posting in this newsgroup:

>>> def f(): a=b=c
...
>>> import dis
>>> dis.dis(f)
          0 SET_LINENO               1

          3 SET_LINENO               1
          6 LOAD_GLOBAL              0 (c)
          9 DUP_TOP
         10 STORE_FAST               0 (a)
         13 STORE_FAST               1 (b)
         16 LOAD_CONST               0 (None)
         19 RETURN_VALUE

-- 
Frank Buß, fb at frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de



More information about the Python-list mailing list