Searching through a dictionary for users input - python

Hello everyone so I have an issue trying to find the user input in a dictionary.
My function is getting data from a website and writing it to a text file. Then transferred into a dictionary, from there I will ask the user to input a country name and it will return the key and the value of that key or the capita income. The issue i am having is that i have to search the dictionary to find the input and if it matches the key then it will print that and the capita income. Im not 100 percent sure what to use if i should use a for function or if my code is correct at the end.
def main():
import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile) #connects to the file and gest a response object
with open("capital.txt",'wb') as f:
f.write(data.content) #write the data out to a file – wb used since thecontent from the response object is returned as abinary object.
f.close()
countryName = {}
with open('capital.txt','r') as infile:
for line in infile:
num,*key,value = line.split()
key = ' '.join(key)
countryName[key] = value.upper()
userInput = input("Enter a country name: ")
userInput.upper()
while(userInput != 'stop'):
#for loop to see if key is in dictionary
if userInput in countryName:
#if(userInput == countryName[key]):
print("The per capita income in",key, "is",countryName[key])
userInput = input("Enter a country name: ")
main()
while(userInput != 'stop'):
#for loop to see if key is in dictionary
if userInput in countryName:
#if(userInput == countryName[key]):
print("The per capita income in",key, "is",countryName[key])
userInput = input("Enter a country name: ")
main()
Here is where the issue is, tying to find the if the userInput is the same as the country name key . What would i have to do search the dictionary to match the key to the input, or if there is any uneccesary things in my code.

Update 2
Ah, there was a small issue when comparing the keys. Actually, you were doing upper() on the value (a number) which doesn't make sense.
Have a look at this update:
import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile)
with open("capital.txt",'wb') as f:
f.write(data.content)
countryName = {}
with open('capital.txt','r') as infile:
for line in infile:
num, *key, value = line.split()
key = ' '.join(key)
countryName[key.upper()] = value #key.upper() instead of value.upper()
userInput = input("Enter a country name: ").upper()
counter = 0
while not userInput == "STOP": #'STOP' because it's uppercase
if userInput in countryName:
print("The per capita income in", userInput, "is", countryName[userInput])
userInput = input("Enter a country name: ").upper()
counter += 1
if counter >= len(countryName): #It couldn't find the country
userInput = input("Not found. Enter a new country: ").upper()
counter = 0 #Let's try again
And a small improvement: the counter will prevent the infinite loop when the user input doesn't satisfy the if userInput in countryName and it's not "stop". Besides that, the "stop" condition must be "STOP", once it'll be in upper case.
Hope it helps
Update
As pointed out by #Barmar, another possibility is:
countryName = {
"countryA": "valueA",
"countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
if userInput in countryName:
print ("The country is", userInput, "and the value is", countryName[userInput])
Just a good advice: I think the file part has nothing to do with your question itself, so, next time try to reduce your problem to, you know, something more direct :)
Anyway, you can loop over the keys of countryName and then compare with the user input. In other words:
countryName = {
"countryA": "valueA",
"countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
for key in countryName.keys():
if userInput == key: #Got it
print ("The country is", key, "and the value is", countryName[key])
Hope it helps

Related

Export quiz result to a text file in Python

Is it possible to have questions and answers exported to a text file such as result.txt?
I answer all the questions and at the end - all the information is saved in a txt file as a list, that can be viewed later.
Example:
Question 1
Answer 1
Question 2
Answer 2
...
I was wondering about file=open, but would that be right?
And how do I export input questions with file open?
I hope you can help.
from datetime import date
today = date.today()
date = today.strftime("%d.may, %Y.year\n")
print("Today is:", date)
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
while True:
name = input("Let's see!\nWhat is your name? ")
description = input("Enter a description of the environmental pollution: ")
city = input("In which city is environmental pollution observed? ")
address = input("Enter your residential address: ")
try:
question = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n" ))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if question == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif question == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
As you wanted the file content as a key-value pair, initialize a dictionary and add the corresponding values, instead of using separate variables for names, descriptions, etc. use them as dictionary keys.
First, initialize a global dictionary
global mydict
Initialize it in Vide() function. (use of global keyword because mydict is being modified in a function)
global mydict
mydict = {}
Store question and answer as a key-value pair
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
In try block:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
Now the if-else statements:
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
After calling the function Vide(), write your dictionary to a file
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
Whole code
global mydict
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
global mydict
mydict = {}
while True:
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
try:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
This can be done by writing or appending to a text file. You are correct, we can use the file = open structure to achieve this. I suggest writing something like the following:
file = open('results.txt', 'w')
Then use the following to write to the file once it has been opened.
file.write("Use your variables and questions from before to print user entered data")
Don't forget to close the file once you're done!
file.close()

How to print a specific line/row from a text file?

I have a text file as following:
1, Max Mustermann, Male, 1000.0
2, Nora Mustermann, Female, 790.0
3, Tomas Mustermann, Male, 400.0
i want to read the last value from the fourth column if i type the persons number and the number 1 to show the value. Unfortunately, I can't get any further from here. How can i do this?
data_next = []
for data in open("my_data.txt"):
liste = data.split(",")
number = int(liste[0])
name = liste[1]
sex = liste[2]
value = liste[3]
data_next.append(number)
print(f" [{number}] {name} {sex} {value}")
which_person = int(input("WHICH PERSON?: "))
if which_person in data_next:
print("Do you want to know the value? Press 1 for YES or 2 for NO")
next_input = int(input("YOUR INPUT: "))
if next_input == 1:
print(value)
elif next_input == 2:
print("THX")
You need to save the values as well in the structure, a dict is very well suited for that : number as key, values as value
data_next = {}
with open("my_data.txt") as fic:
for data in fic:
liste = data.split(",")
number = int(liste[0])
data_next[number] = liste[1:]
print(f" [{number}] {liste[1:]}")
Then use the dict, to access the values
if which_person in data_next:
print("Do you want to know the value? Press 1 for YES or 2 for NO")
next_input = int(input("YOUR INPUT: "))
if next_input == 1:
print(data_next[which_person][2])
elif next_input == 2:
print("THX")
With regex you can handle nicely the comma+space delimiter
data_next = {}
with open("my_data.txt") as fic:
for data in fic:
nb, *others = re.fullmatch(r"(\d+),\s*([^,]+),\s*(\w+),\s*(\d+.?\d*)", data).groups()
data_next[nb] = others
print(f" [{nb}] {' '.join(others)}")
which_person = input("WHICH PERSON?: ")
The for-loop at the beginning of your code succeeds in placing all of the 'values' from the text file into one list.
data_next = ["1000.0", "790.0", "400.0"]
However, that list isn't useful for what you are trying to do below, which is to take input for one of the names from the data file and print the corresponding number. What you want for this is a dictionary, which links from one value to another. To achieve this, use the following code:
# set data_next to an empty dictionary
data_next = {}
for data in open("my_data.txt"):
liste = data.split(",")
number = int(liste[0])
name = liste[1]
sex = liste[2]
value = liste[3]
# set the current number equal to the current value in the dictionary
data_next[number] = value
print(f" [{number}] {name} {sex} {value}")
which_person = int(input("WHICH PERSON?: "))
# data_next.keys() will return an iterable of all of the id numbers in the dictionary
if which_person in data_next.keys():
print("Do you want to know the value? Press 1 for YES or 2 for NO")
next_input = int(input("YOUR INPUT: "))
if next_input == 1:
# data_next[which_person] will return the value in the dictionary assigned to the number which_person
print(data_next[which_person])
elif next_input == 2:
print("THX")
Another thing:
This code will perform slightly differently than you expect because of how the file is formatted When you split each line by ",".
"1, Max Mustermann, Male, 1000.0".split(",") == ["1", " Max Mustermann", " Male", " 1000.0"]
As you can see, the spaces after each comma are included with the next value. To fix this, change the split statement to split(", ") instead of split(",") OR remove the spaces after the commas in the file.
maybe the easyst way is
from csv import reader
from sys import exit
def get_person_row(number:int)->list or None:
with open('my_data.txt','r') as file:
table= reader(file)
for row in table:
if int(row[0]) == number:
return row
try:
which_person = int(input("WHICH PERSON?: "))
except ValueError:
print('just numbers are valid for Id')
exit(1)
line = get_person_row(which_person)
if line is None:
print('invalid id')
else:
print(str(line))

Printing values from dictionary

I am having problems printing values from a dictionary I made. The dictionary contains a word as a key and a description of that word as a value. The problem I run into is in the function that is supposed to print the description of a word (lookup) that the user puts in is not working as I want it to.
I have implemented a for loop to search for the word the user wants to look up in the dictionary and then print the description (value) of that word. and it kinda works. The problem is that if for example, the dictionary would have a word: banana and apple and description: yellow and fruit. It will work if I want to look up "apple". Then it will print "description of apple: fruit".
The problem appears if I then want to look up the description of "banana". Because it is a loop (and the latest value of word was apple I guess) it will first go through and print "the word is not in the dictionary!" and then print "description of banana: yellow". So I'm thinking to get past this problem I should implement another way of finding the key than a loop. I just don't know how.
def dictionary():
dictionary = {}
while True:
print("\n--- Menu for dictionary ---\n Choose 1 to insert a new word\n Choose 2 to find the description of a word\n Choose 3 to exit\n")
answer = input("Type your answer here: ")
if answer == "1":
insert(dictionary)
elif answer == "2":
lookup(dictionary)
elif answer == "3":
break
else:
print("\nTry again!\n")
def insert(dictionary):
word = input("Type the word you want to add: ")
description = input("Type a description of the word: ")
if word in dictionary:
print("\nThe word already exists in the dictionary!\n")
return
else:
dictionary[word] = description
def lookup(dictionary):
wordsearch = input("What word would you like to lookup: ")
for word, description in ordlista.items():
if word == wordsearch:
print("\nDescription of", word,":", description)
break
else:
print("The word is not in the dictionary!")
You just need to remove the else condition and make sure that you print the second statement only when the loop is over (and never hit the break part).
With the current version of your code that conditional is execute for every iteration of the loop so if it fails it just prints the "Not found".
Here's an example:
def dictionary():
dictionary = {}
while True:
print("\n--- Menu for dictionary ---\n Choose 1 to insert a new word\n Choose 2 to find the description of a word\n Choose 3 to exit\n")
answer = input("Type your answer here: ")
if answer == "1":
insert(dictionary)
elif answer == "2":
lookup(dictionary)
elif answer == "3":
break
else:
print("\nTry again!\n")
def insert(dictionary):
word = input("Type the word you want to add: ")
description = input("Type a description of the word: ")
if word in dictionary:
print("\nThe word already exists in the dictionary!\n")
return
else:
dictionary[word] = description
def lookup(dictionary):
wordsearch = input("What word would you like to lookup: ")
for word, description in dictionary.items():
if word == wordsearch:
print("\nDescription of", word,":", description)
break
print("The word is not in the dictionary!")
dictionary()
I also want to add that looping through all the values in the dictionary may not be very efficient if your dictionary is very big.
For this reason I'd like also to suggest another solution using using get():
def dictionary():
dictionary = {}
while True:
print("\n--- Menu for dictionary ---\n Choose 1 to insert a new word\n Choose 2 to find the description of a word\n Choose 3 to exit\n")
answer = input("Type your answer here: ")
if answer == "1":
insert(dictionary)
elif answer == "2":
lookup(dictionary)
elif answer == "3":
break
else:
print("\nTry again!\n")
def insert(dictionary):
word = input("Type the word you want to add: ")
description = input("Type a description of the word: ")
if word in dictionary:
print("\nThe word already exists in the dictionary!\n")
return
else:
dictionary[word] = description
def lookup(dictionary):
wordsearch = input("What word would you like to lookup: ")
if dictionary.get(wordsearch):
print("\nDescription of", wordsearch,":", dictionary.get(wordsearch))
else:
print("The word is not in the dictionary!")
dictionary()
Here's some basic information the Get method I used:
Get Parameters
get() Parameters get() method takes maximum of two parameters:
key - key to be searched in the dictionary value (optional) - Value to
be returned if the key is not found. The default value is None. Return
Value from get() get() method returns:
the value for the specified key if key is in dictionary. None if the
key is not found and value is not specified. value if the key is not
found and value is specified.
Get returns
Return Value from get() get() method returns:
the value for the specified key if key is in dictionary. None if the
key is not found and value is not specified. value if the key is not
found and value is specified.
More information about the Python dictionary's get() method available here.
Norie has it right - here's a little more detail. Your function:
def lookup(dictionary):
wordsearch = input("What word would you like to lookup: ")
for word, description in ordlista.items():
if word == wordsearch:
print("\nDescription of", word,":", description)
break
else:
print("The word is not in the dictionary!")
can be rewritten to use get instead of iterating through the keys:
def lookup(dictionary):
wordsearch = input("What word would you like to lookup: ")
look_result = ordlista.get(wordsearch)
print(f"\nDecription of {word}: {look_result}" if look_result else "\nThe word is not in the dictionary!")

I made a dictionary, I am struggling with print x number of times that user inputs

This is my dictionary:
def get_dic(filename):
count = 0
db = {}
filename = "words.txt"
with open(filename, "r") as infile:
for line in infile:
if line:
eng_words, spa_words = line.rstrip().split(":")
key = eng_words
val = spa_words.split(",")
db[key] = val
count += 1
print(count, "entries found.")
return db
this is the file it reads from and converts it to a dictionary:
library:la biblioteca
school:el colegio,la escuela
restaurant:el restaurante
movie theater:el cine
airport:el aeropuerto
museum:el museo
park:el parque
university:la universidad
office:la oficina,el despacho
house:la casa
Now I wanna call my db and make a "quiz" game using random() method after user inputs a number from 1 to 10. Since my list is only 10 lines.
import random
def main():
db = get_dic(filename)
random.shuffle(db)
for keyword in db(10):
display = "{}"
print(display.format(keyword))
userinput = input("Enter 1 equivalent Spanish word(s). Word [1]: ")
print(db[keyword])
print(" ")
if userinput == (db[key]):
print("correct!")
correct += 1
If input is "5", how do I get the program to print 5 words?
And I wanna return the score "correct" into another function that is not main(). Which will later write the score to a seperate .txt file, Is this possible? Do I just "return correct" and call it in a function like usual? I've only seen codes call function in "def main():"
output example if input choosen is 2:
English word: museum
Enter 1 equivalent Spanish word(s). Word [1]: el museo
Correct!
---
English word: school
Enter 2 equivalent Spanish word(s). Word [1]: el colegio
Word [2]: la escuela
Correct!
This may be what you want. I ask the user how many rounds first. (I have not validated this input, though)
def main():
db = get_dic(filename)
keys = list(db.keys())
random.shuffle(keys)
rounds = int(input('Enter a number of rounds (1-10): '))
correct = 0
for keyword in keys[:rounds]:
print(keyword)
userinput = input("Enter 1 equivalent Spanish word(s). Word [1]: ")
print(db[keyword])
print(" ")
if userinput == (db[keyword]):
print("correct!")
correct += 1
return correct
correct = main()
print(f'{correct} answers correct')
to validate the input you can also do
def get_num(text,err_text,verify):
try:
the_input = int(input(text))
if verift(the_input):
return the_input
else:
print(err_text)
return get_num(text,err_text)
except:
print(err_text)
return get_num(text,err_text)
#...
rounds = get_num('Enter a number of rounds (1-10): ', 'please enter an integer between 1 and 10', verify=lambda x:x>0 and x <11)

I am trying to create an address book program that will append user input to its appropriate list

I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()

Categories

Resources