I defined a defaultdict as follows:
results=defaultdict(list)
In a for loop that reads through each line in my dictionary file, I generate a tempWordObject that contains the original word (originalWord), its alphabetized version (azWord), and the length of the word (wLength). I then append the object to a list based on its length:
results[tempWordObject.wLength].append(tempWordObject)
So, what I should end up with, is a defaultdict called results that has lists of words based on their lengths. So, for example, results[4] should contain all 4 letter words in a list. Please correct me if I'm misunderstanding what is happening.
What I'm trying to do (for testing purposes and to generate results later) is print all lists I have in defaultdict after I'm done reading through the file. So, it will print the list of word objects defaultdict[1] in the first line, the list of word objects in defaultdict[2] in the second line, etc. I would also like to be able to print only a specific parameter when I do this.
If it's of any help, I will have the length of the longest word (maxL) once the loop is done.
I think part of the reason I couldn't get this working is due to me misunderstanding how ever is stored in defaultdict and/or how I'm storing it. An explanation would be much appreciated.
Just loop over the keys, in sorted order:
for length in sorted(results):
print length, [t.originalWord for t in results[length]]
A defaultdict
is still a dictionary; sorted(results)
returns a list of all the keys in that dictionary, sorted. Using each key you can then access the stored lists of your special objects again, with results[length]
. The list comprehension merely pulls out each originalWord
attribute from those objects.