Kelvin Davis Kelvin Davis - 19 days ago 6
Python Question

Dictionary Key:Value removal and re instertion into a list or something

So I'm attempting to make a hangman game for practice. I've wrote the function to get the random word and a function to pair those characters up with there index. Wondering if the user guess a correct character is there a way to reference the dictionary, and output the character to an empty list at the correct index? Code I Have so far:

import random
import sys

def hangman():
print("Welcome to Hangman\n")
answer = input("Would you like to play? yes(y) or no(n)")
if answer is "y":
print("Generating Random Word...Complete")
wordlist = []
with open('sowpods.txt', 'r') as f:
line = f.read()
line = list(line.splitlines())
word = list(random.choice(line))
Key = matchUp(word)


else:
sys.exit()

def matchUp(word):
list = []
for x in word:
list.append(word.index(x))
newDict = {}
newDict = dict(zip(word, list))
return newDict

hangman()

Answer

So like this? You can skip the whole dictionary thing...

a = "_" * len(word)

def letter_check(letter):
    if letter in word:
        a[word.index(letter)] = letter
        # possibly print 'a' here
    else:
        # function for decrement tries here

EDIT: Ooops... I forgot about potential repeated letters... um... how about this:

a = "_" * len(word)

def letter_check(letter):
    if letter in word:
        for x, y in enumerate(word):
            if letter == y:
                a[x] = letter
    else:
        # function for decrement tries here
Comments