Attribute error in python won't go away
Question: Why do I keep getting

    
    
    AttributeError: 'dict_keys' object has no attribute 'sort'
    

or my code? How can I fix this?

    
    
    import string
    
    infile = open('alice_in_wonderland.txt', 'r')
    
    text = infile.readlines()
    
    counts = {}
    
    for line in text:
        for word in line:
        counts[word] = counts.get (word, 0) +1
    '''
    if word != " ":
    if word != ".":
    '''         
    
    word_keys = counts.keys()
    word_keys.sort()
    
    infile.close()
    
    outfile = open("alice_words.txt", 'w')
    outfile.write("Word \t \t Count \n")
    outfile.write("======================= \n")
    for word in word_keys:
    outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
    outfile.close()
    

I'm not sure what else to do.


Answer: To produce a sorted list of keys, use:

    
    
    word_keys = sorted(counts)
    

instead. This works in both Python 2 and 3.

In Python 3 `dict.keys()` does not return a list object, but a [dictionary
view object](https://docs.python.org/3/library/stdtypes.html#dictionary-view-
objects). You could call `list()` on that object, but `sorted()` is much more
direct and saves you two additional calls.

I see that you appear to count words in a file; if so, you are instead
counting _characters_ , not words; `for word in line:` iterates over a string,
so `word` is assigned individual characters from the line.

You should be using
[`collections.Counter()`](https://docs.python.org/2/library/collections.html#collections.Counter)
instead:

    
    
    from collections import Counter
    
    counts = Counter
    
    with open('alice_in_wonderland.txt') as infile:
        for line in infile:
            # assumption: words are whitespace separated
            counts.update(w for w in line.split())
    
    with open("alice_words.txt", 'w') as outfile:
        outfile.write("Word \t \t Count \n")
        outfile.write("======================= \n")
        for word, count in counts.most_common():
            outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
    

This code uses the file objects as context managers (with the `with`
statement) to have them closed automatically. The `Counter.most_common()`
method takes care of the sorting for us, not by key but by word count.

