writing to lists within a dictionary

C

cokofreedom

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)
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
 
D

Duncan Smith

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)
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top