[Tutor] two way dictionary
ingo janssen
ingoogni at gmail.com
Wed Nov 28 19:53:03 CET 2007
for a little cherrypy app I'm working on I wrote the piece of code
below. Goal is to obscure the first part of a directory path(s) the
user is browsing. Replacing the first part of the path with an alias
works fine, but for the application it has to work both ways. I know
how to swap the keys and values of the dict but that's not elegant as
it can be changed over time.
Is there a dict that works "both ways"?
Could a dict be constructed from the dict class that works both ways?
Is writing code around a list of tuples more elegant? home = [('one' ,
"c:\\gnuwin32"), ('two' , "c:\\dell")]
Did I miss the completely obvious way to deal with the problem?
%<-----%<-----%<-----%<-----%<-----%<-----
import os
home={
'one':"c:\\gnuwin32",
'two':"c:\\dell",
}
def fetch_alias(path, home_dict):
path = os.path.normpath(path)
pathlist = path.split(os.sep)
if pathlist[0] in home_dict:
pathlist[0] = home_dict[pathlist[0]]
newpath = os.sep.join(pathlist)
return os.path.normpath(newpath)
else:
print "fail"
path='two\\truus\\tovert\\konijn'
print fetch_alias(path, home)
%<-----%<-----%<-----%<-----%<-----%<-----
Ingo
More information about the Tutor
mailing list