reversing a dictionary (newbie)
Steve Purcell
stephen_purcell at yahoo.com
Thu Mar 15 05:31:34 EST 2001
Christopher Brewster wrote:
> I have written a program to extract pairs of words from a corpus (the BNC).
> It is my first Python program
> Once it has processed the files I "reverse" the dictionary so that the keys
> are frequencies and the values lists of word pairs of that frequency.
What if two words have the same frequency? You probably want the 'reversing'
process to generate a list of (frequency, word) tuples.
But anyway... to reverse a dictionary, you can do:
>>> dict = {'a':1, 'b':2, 'c':3}
>>> reversed = {}
>>> for k, v in dict.items():
... reversed[v] = k
>>> reversed
{3: 'c', 2: 'b', 1: 'a'}
Expect total memory usage to be triple that of 'dict' alone towards the end
of the loop, because of the 'items()' call.
-Steve
--
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo
More information about the Python-list
mailing list