Python 3.x : using a list, if a letter isn't in that list, add it. otherwise, increment the value by 1
<p>so this is what I'm doing: I'm pulling up a file and having the program read it. Every time it encounters a letter, it'll add the letter to list1 and add '1' to list2. Every time it encounters a letter in list1, it'll increment list2 by 1. </p>

<pre><code>txt = open("Nameoffile.txt")
wordcount = 0
Charcount = 0
letterlist = [] #list 1
lettercount = [] #list 2

for words in txt:
    print(words)
    for letters in words:
        if letters not in letterlist:
           letterlist.append(letters)
           lettercount[letters] = 1
        else:
           lettercount[letters] += 1

        Charcount += 1
        print(letters)
        if letters == ' ':
           wordcount += 1
        if letters == '.':
           wordcount += 1
        if letters == '\n':
           Charcount -= 1
           wordcount += 1

#down here it would print the results
</code></pre>

<p>the problem I'm running into is that when running this, I get the following error:
line 14, lettercount[letters] = 1
TypeError: list indices must be integers or slices, not str</p>

<p>I assumed I could get away with stating that at list[letter] set that value to a number, but it isn't liking it. any possible hints on what to do?</p>

<p>Lists work with integer indexes, you can use a dictionary instead:</p>

<pre><code>lettercount = {} #list 2
</code></pre>

<p>Dictionaries have the capacity to store key, values objects, so you can use not numeric keys to acees values. Their use is similar to the lists so you can still use:</p>

<pre><code>lettercount[letters] = 1
</code></pre>

<p>to add or update a key in the dictionary, however they are not iterable as lists, you have to iterate them using keys or iteritems methods.
To print the results you can iterate over the keys and display the count:</p>

<pre><code>for e in lettercount.keys():
    print (e, str(lettercount[e]))
</code></pre>

python list python-3.x append increment