pythonlistdictionaryparsingnested

Parsing a list nested within a dictionary for words with similar characters in Python


As my first personal project I am building a Wordle "solver" that comes up with a first guess word then takes an input of the letters that were correct in the word then searches the word list for words with similar characters. To do this I stored each word in a dictionary with the key being the word and the value being each character in the word i.e dodge: [d, o, d, g, e]. I am currently experimenting to get code running that parses through the values of the dictionary to match the characters to the inputted letters but am stumped on how to search through the lists within the dictionary as a loop.

Here's my code for inputting the correct letters:

correct_letters_1 = list(letters for letters in input("Input corrects letters: ").strip().split())

Here's one of my attempts at parsing the dictionary:

for letters in correct_letters_1: 
    if letters in word_dictionary.values(): 
       print("yes")

I'm pretty sure this problem has something to do with my code parsing the entire lists within the dictionary rather than each individual character but even when I try inputting the whole word, i.e Input Correct Letters: d o d g e; I still don't have any output.

If someone could put a beginner on the right track it would be much appreciated.


Solution

  • You might be looking to compare the whole list, rather than the letters:

    correct_letters_1 = list(input("Enter correct letters: ").strip())
    
    # correct_letters_1 is a whole list
    if correct_letters_1 in word_dictionary.values():
        print("yes")
    

    # Inputting "abc"
    >>> correct_letters_1
    ['a', 'b', 'c']
    >>> word_dictionary
    {'abc': ['a', 'b', 'c']}
    >>> correct_letters_1 in word_dictionary.values()
    True
    

    To check if the user's guess is a subset of any of the words:

    correct_letters_1 = list(input("Enter correct letters: ").strip())
    let_set = set(correct_letters_1)
    
    word_dictionary = {'abc': ['a', 'b', 'c'],
                       'abcde': ['a', 'b', 'c', 'd', 'e'],
                       'ab': ['a', 'b'],
                       'test': ['t', 'e', 's', 't']}
    
    # Check to see if correct_letters_1 is a subset of any word in the dictionary
    close_words = ["".join(x) for x in word_dictionary.values() if let_set <= set(x)]
    

    Which can be simplified to:

    correct_letters_1 = input("Enter correct letters: ").strip()
    let_set = set(correct_letters_1)
    
    words = ["abc", "test", "ab"]
    
    # Check to see if correct_letters_1 is a subset of any word in the list words
    close_words = [x for x in words if let_set <= set(x)]