Rookie question about data types (hashtables)

Axel Mittendorf newsreply at transfertech.de
Thu Jan 29 08:44:56 EST 2004


"Steve D. Perkins" <dontwritesteve at hotmail.com> wrote:
> Hello all -
Hi

> when you type the letter "a" the box will contain all English words
> starting with the letter "a".  When you then type "n", the box will
> narrow further and contain all words starting with "an", etc... until

Maybe you could use a normal python dictionary (you call it hashtable).
Look at this script (You would need one dictionary for each direction.):

#!/usr/bin/python

# generate dictionaries (AKA hashtables).
# direction: English --> German
EN2DE = {}
# direction: German --> English
DE2EN = {}

# inserts a word and its translation into the dict d
def insertWord( d, key, val):
    # does the key exist
    if d.has_key( key):
        # yes
        d[ key].append( val)
    else:
        # no
        d[ key] = [val]

# returns a list words that begin with s
def getBeginWith( d, s):
    l =  s.__len__()
    res = []
    keys = d.keys()
    for k in keys:
        if k.__len__()>=l and k[:l] == s:
            # use "k[:l].lower() == s.lower()" to ignore case
            res.append( k)
    return res

# insert some entries
insertWord( EN2DE, "someword", "meaning 1")
insertWord( EN2DE, "someword", "meaning 2")
insertWord( EN2DE, "my_codingstyle", "evil")
insertWord( EN2DE, "son", "Sohn")
insertWord( EN2DE, "sunday", "Sonntag")
insertWord( EN2DE, "wednesday", "Mittwoch")
insertWord( EN2DE, "Weapon of mass destruction", "George Walker Bush")
insertWord( EN2DE, "sold", "verkauft")

# show that it works
print "all keys that begin with 'so': ", getBeginWith( EN2DE, "so")
print "translations for 'someword': ",  EN2DE['someword']

Instead of doing this you could maybe subclass UserList from the standard
library.
> Steve

HTH, Axel





More information about the Python-list mailing list