Python Dictionary holding wrong values

I am creating a hangman algorithm in Python as a learning project, I have a list of words the computer picks at random and filters etc. It has 8 lives to guess the word.

I have a dictionary in python called a_count - which stores the frequency of each letter in a specific list. The plan was to start off with a list of 12500 words, calculate the max frequency (nGuess) and then filter the list based on whether it does or does not contain that word. It then removes the letter nGuess from a_count so it doesn't try to pick the same letter again.

My issue is my list of words nlist is being filtered correctly (down to 125 in the final iteration) and the length of a_count appears to be removing letters accordingly (down to 17 in the last iteration however, a_count appears to be holding on to values from maybe the first time I initialized values to it.

{'H': 1682, 'D': 2364, 'G': 1576, 'B': 1547, 'C': 1947, 'K': 1426, 'F': 1071, 'M': 1908, 'P': 1945, 'Y': 1992, 'W': 1013, 'V': 661, 'Z': 412, 'X': 268, 'J': 270, 'Q': 104}

My list of words is 125 at this point so the sum of values should equal 625 (5*125)

The code is as below:

while life > -1 and pos < 5:
  if life == 0:
    loses = loses + 1 

  nword = []
  word = []
  letters = []
  chars = []

  for word in nlist:
    for letters in chars:
        a_count[letters] = a_count.get(letters, 0) + 1
  for x in blacklist:
    a_count.pop(x, 0)

  for x in whitelist:
    a_count.pop(x, 0) 

  nGuess = (max(a_count.items(), key=operator.itemgetter(1))[0])

  print(str(nGuess) + ' is my next guess')

  nlist = []
  flist = []
  hlist = []
  for g in nword:
    if nGuess in g:

  for g in nword:
    if nGuess not in g:

  if nGuess in tokens:
    nlist = flist
    print(str(nGuess) + ' is in the word')
    pos = tokens.count(nGuess) + pos
    nlist = hlist
    life = life - 1
    print(str(nGuess) + ' is not in the word, I have ' + str(life) + ' lives left')

  if pos == 5:
    wins = wins + 1

Can anyone see what the issue is? Am I right in saying after the first iteration (not shown in the code) is that storing the values in the dictionary, and then subsequent a_count is adding to the current list? As the pop is working, I'm just not getting the count's I would expect.

Even when I was left with a list of 4 words it was choosing a letter than wasn't even in any of those words! So the issue definitely lies with a_count

Thanks in advance!

Read more here:

Content Attribution

This content was originally published by KDE at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: