question about dictionary type..

Frank Buss fb at frank-buss.de
Sat Sep 14 17:30:56 EDT 2002


eugene kim <eugene1977 at hotmail.com> wrote:

> 
> thank you.. i just checked replies..
> i haven't tried them..
> this is what i came up with..
> (making needed tables first.. as carl and padraig said)
> i'm having one problem(described below)

Your code doesn't look very Python-like, but I'm no expert :-)

Do you know regular expressions? If you use my add-function, you can write 
the following:

-----------------------------------------
from string import upper
from sys import stdin
import re

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

tree={}
records = re.compile('\((.*?)\)', re.DOTALL).findall(stdin.read())
for record in records:
  fields = map(lambda w: upper(w), re.findall("'(.*)'", record))
  add(tree, (fields[0],fields[2],fields[3]),0)
  add(tree, (fields[1],fields[2],fields[3]),0)

print tree
-----------------------------------------

With your testdata the output will be:

{'BAYLOR': {'FOOTBALL': {'M': 0, 'F': 0}}, 'CALIFORNIA': {'FOOTBALL': 
{'M': 0}}, 'NEW MEXICO': {'FOOTBALL': {'M': 0}}, 'SAMFORD': {'FOOTBALL': 
{'F': 0}}}

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