user1768884
user1768884

Reputation: 1047

using tuples as a dictionary key in an anagram finder in python

So I am writing a program that reads from a word file and prints out sets of words that are anagrams.

Currently, I have a function that takes a string, and returns a tuple with the letters all sorted out.

def getLetters(string):
    """Purpose, to nab letters from a string and to put them in a tuple in
    sorted order."""
    tuple_o_letters = sorted(tuple(string))
    if _DEBUG:
        print tuple_o_letters

    return tuple_o_letters

Sent to this function is this code

try:
    fin = open("words.txt")
except:
    print("no, no, file no here.")
    sys.exit(0)

wordList = []
for eachline in fin:
   wordList.append(eachline.strip())
for eachWord in wordList:
   getLetters(eachWord)

Now, while I can make tuples easily, where I am stuck is I'm trying to store these as dictionary keys, which would be optimal since tuples and keys are immutable, but I'm confused on the method of doing this. Also, the values would be lists of the words with these keys.

Upvotes: 0

Views: 478

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

sorted() returns a list, you want to swap your line:

tuple_o_letters = tuple(sorted(string))

which sorts the letters in string, then turns the resulting sorted list into a tuple.

Upvotes: 3

Related Questions