Fahzz
Fahzz

Reputation: 33

How can I convert a text file to a dictionary to be used in Python?

I am doing a small programming project for school, one of the main elements of my program is to be able to allow the user to enter a problem (e.g. "my phone screen is blank") and for me to iterate through each word of the string and compare it to a dictionary, and the dictionary must be an external text file, I would like help on the dictionary aspect of this. I have tried a few other methods from different posts of stack overflow but they do not seem to work.

Some lines of my dictionary include:

battery Have you tried charging your phone? You may need to replace your battery.
sound Your volume may be on 0 or your speakers may be broken, try using earphones.
blank Your screen may be dead, you may need a replacement.

Here, "battery,"sound" and "blank" are they keys with their respective values following on after, how do I plan on doing this?

Thank you!


[edited code]

def answerInput():
    print("Hello, how may I help you with your mobile device")
    a = input("Please enter your query below\n")
    return a

def solution(answer):
    string = answer
    my_dict = {}
    with open("Dictionary.txt") as f:
        for line in f:
            key, value = line.strip("\n").split(maxsplit=1)
            my_dict[key] = value
            for word in string.split():
                if word == my_dict[key]:
                    print(value)
            
process = 0
answer = answerInput()
solution(answer)

Upvotes: 0

Views: 59

Answers (1)

GAP2002
GAP2002

Reputation: 979

my_dict = {}  # defining it as a dictionary
with open("file.txt") as f:  # opening txt file
    for line in f:
        key, value= line.strip("\n").split(maxsplit=1)  # key is before first whitespace, value is after whitespace
        my_dict[key] = value

This will work well, something I have used personally. It initiates a dictionary called my_dict, opens the file and for each line it strips \n from the line and splits it once only. This creates two values which we call key and value which we add to the dictionary in the form {key: value}

Or, using dict comprehension

with open("file.txt") as f:  # opening txt file
    my_dict = {k: v for k,v in (line.strip("\n").split(maxsplit=1) for line in f)}

Upvotes: 3

Related Questions