reversing a dictionary (newbie)
Tim Hochberg
tim.hochberg at ieee.org
Thu Mar 15 10:57:02 EST 2001
"Christopher Brewster" <C.Brewster at dcs.shef.ac.uk> wrote in message :
> The processing of the files is quite quick (700 odd files (@ 100k mean
size)
> of directory 'A' in about 20 minutes)
> but the reversing of the dictionary took hours and hours. I have run the
> program successfully on a PC (500 MHz, 256 RAM, running Windows NT) and I
am
> still waiting for results from a Sun (1 Giga RAM) since yesterday. Here is
> the code - what have I done wrong?
[Reversal function that Outlook mangled anyway]
It's not obvious (to me anyway) why this so slow. There is some extraneous
list munging going on, but I'd be suprised if that slowed things down that
much. In any event here's are two version that might be somewhat faster
(untested):
def revdict1(diction):
"The long form"
revdict = {}
for wordpair in diction.keys():
freq = diction[wordpair]
if revdict.has_key(freq):
revdict[freq].append(wordpair)
else:
revdict[freq] = [wordpair]
return revdict
def revdict2(dict):
"The short form (assumes python 2.0)"
rev = {}
for wp, freq in dict.items():
rev.setdefault(freq, []).append(wp)
return rev
Perhaps that'll help. Who knows?
-tim
More information about the Python-list
mailing list