Pulling Random Row from txt File
I have a text file named universitylist.txt. When the user's input matches the college name, the college and city are returned. I am trying to add an IF statement that will return a random entry from the file when the user enters "random college". I am searching for the best way to do this. I tried appending random.LineItem in the print statement but that doesn't work.
e#!/usr/bin/env python3
from random import random
def main():
print("Welcome to University Locator!")
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
city = ""
while user_input.lower() != "x":
with open("universitylist.txt") as file:
schoollist_dict = {}
for lineitem in file:
lineitem = lineitem.replace("\n", "")
school_city_list = lineitem.split(",")
schoollist_dict.update({school_city_list[0]: school_city_list[1]})
user_college = user_input.title()
**if user_input == "random college":
rando_entry = random.schoollist_dict(lineitem)
print(rando_entry)**
elif user_college in schoollist_dict:
print()
print(f"College: {user_college}")
print(f"City: {schoollist_dict[user_college]}")
print()
else:
print(f"The college {user_college} does not exist in our database.")
print()
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
print("Session Terminated")
if __name__ == "__main__": main() # Main entry point for the applications
nter code here
Add this to your code,
import random #goes on top
random.choice(list(schoollist_dict.values()))
So something like this,
if user_input == "random college":
rando_college, rando_city = random.choice(list(schoollist_dict.items()))
print(rando_college, rando_city)
Make sure you import random
on top.
I created a textfile with 2 columns and the code above works for me when I updated your code with it.
Your final code should look like this,
import random
def main():
print("Welcome to University Locator!")
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
city = ""
while user_input.lower() != "x":
with open("universitylist.txt") as file:
schoollist_dict = {}
for lineitem in file:
lineitem = lineitem.replace("\n", "")
school_city_list = lineitem.split(",")
schoollist_dict.update({school_city_list[0]: school_city_list[1]})
user_college = user_input.title()
if user_input == "random college":
rando_college, rando_city = random.choice(list(schoollist_dict.items()))
print(rando_college, rando_city)
elif user_college in schoollist_dict:
print()
print(f"College: {user_college}")
print(f"City: {schoollist_dict[user_college]}")
print()
else:
print(f"The college {user_college} does not exist in our database.")
print()
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
print("Session Terminated")
if __name__ == "__main__":
main() # Main entry point for the applications