Building and Transvering multi-level dictionaries
Darrell
darrell at dorb.com
Mon Mar 20 21:17:16 EST 2000
[Lee Joramo]
> I am trying to build a multi-level dictionary from an text file, and
> then transverse the dictionary, create formated output. I have been
> able to do this for a special case where ever piece of data has a fixed
> number of levels (sub-catagories). However, I am looking for an method
> that can elegantly handel a dictionary with variable depth.
>
Hope this helps.
import pprint
import re, string
dat="""
animal:mammal:dog A very lazy dog
animal:mammal:dog Super hunting dog
animal:mammal:dog Not your average hound
animal:mammal:cat Enjoys sleeping in the sun
animal:snake Beware of the python in the forest
animal:fish There are many fish in the deep blue sea
animal:fish Tuna terrorize the oceans
plant:tree:evergreen:redwood Very Very Very Tall
"""
def _buildDic(keyList, val, dic):
"""
If performance became a problem this function
would benifit from stackless python.
http://x41.deja.com/getdoc.xp?AN=579586064&CONTEXT=953604693.1731985442&hitn
um=9
"""
if len(keyList)==1:
dic[keyList[0]]=val
return
newDic=dic.get(keyList[0],{})
dic[keyList[0]]=newDic
_buildDic(keyList[1:], val, newDic)
def buildDic(buf, dic=None):
"""
"""
if dic==None:
dic={}
lines= string.split(buf,'\n')
for l in lines:
key=string.split(l)
if len(key) < 2:
continue
keyList=string.split(key[0],':')
_buildDic(keyList,string.join(key[1:]),dic)
return dic
def lookUp(dic,key):
"""
"""
# Not sure about using "." and ":" for separators
keys=string.split(key,'.')
val=dic
for k in keys:
val= val[k]
return val
dataDic=buildDic(dat)
pprint.pprint(dataDic)
print
print lookUp(dataDic,'animal.mammal.cat')
######### output
"""
{'animal': {'fish': 'Tuna terrorize the oceans',
'mammal': {'cat': 'Enjoys sleeping in the sun',
'dog': 'Not your average hound'},
'snake': 'Beware of the python in the forest'},
'plant': {'tree': {'evergreen': {'redwood': 'Very Very Very Tall'}}}}
Enjoys sleeping in the sun
"""
More information about the Python-list
mailing list