writing to lists within a dictionary

Duncan Smith buzzard at urubu.freeserve.co.uk
Thu Sep 20 10:45:24 EDT 2007


cokofreedom at gmail.com wrote:
> 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
> 

A few suggestions.

Use string methods, rather than the string module.
Replace getChar with a simple one-liner (check out the builtin 'sorted'
function).
Consider whether it's really necessary to iterate over all the
dictionary keys.
Check out the setdefault method of dictionaries.

Duncan



More information about the Python-list mailing list