writing to lists within a dictionary

cokofreedom at gmail.com cokofreedom at gmail.com
Thu Sep 20 08:37:05 EDT 2007


I am trying to write a basic anagram system, that takes a text file
line by line and by sorting the string into its alphabetical form
compares it to keys within a dictionary.

If it matches a key I want to add it (in its unordered form) to a list
for that key.

So far this is what I have

import sys, string, fileinput

# takes an item (string) and converts it to its basic alphabetical
form
def getChar( item ):
	item_chars = []
	for i in range(len(item)):
		item_chars.append(item[i])
	item_chars.sort()
	return string.join(item_chars, "")

anagramDict = {}

for line in fileinput.input("fakelist.txt"):
	myLine = line.replace("\n", "") #remove the carriage returns
	myString = getChar(myLine) #get the alphabetical form
	for k in anagramDict.items(): #iterator through the keys in the
dictionary
		if k[0] == myString: #if the key matches our string
			anagramDict[k].append([myLine])#append that k and add the value
this line
	else:
		anagramDict[myString] = [myLine] #else there is no key the same so
make a new one

print anagramDict




More information about the Python-list mailing list