Trouble with reading a dictionary file - python-3.x

Hi my assignment is to read the company names and the shorten names of the companies.
This file with tickers below is given:
ticker_symbol.txt
YAHOO:YHOO
GOOGLE INC:GOOG
Harley-Davidson:HOG
Yamana Gold:AUY
Sotheby's:BID
inBev:BUD
So I need to make 3 functions: def tickers_to_dict(filename), def name_to_symbol(name, ticker_dict) and def symbol_to_name(symbol, ticker_dict).
In the function tickers_to_dict(filename), I need to convert the text file into a dictionary and return it which I have done succesfully.
In the functions def name_to_symbol(name, ticker_dict) and def symbol_to_name(symbol, ticker_dict), I need to find the ticker symbol in the dictionary by the input of the company name and the reverse. (by a input of a ticker symbol it needs to find the company name). But I dont know how to solve this two functions. Can someone help me? So far I have this:
def tickers_to_dict():
ticker_dict = {}
bestand = open('ticker_symbol.txt', 'r')
tickers = bestand.readlines()
for line in tickers:
k, v = line.split(':')
ticker_dict[k] = v
return (ticker_dict)
print(tickers_to_dict())
def name_to_symbol(name, ticker_dict):
output needs to be like this:
Enter Company name: YAHOO
Ticker symbol: YHOO
Enter Ticker symbol: BUD
Company name: inBev

I am not sure this ist what you were looking for but here you go:
def name_to_symbol(mydict):
given_input = input("Enter company name: ")
try:
print("Ticker symbol: ", mydict[given_input])
except:
print("False Input")
def symbol_to_name(mydict):
given_input = input("Enter ticker: ")
for key, value in mydict.items():
if given_input == value:
print("Company name: ", key)
return
print("False Input")
I hope this helped you out. If you want to know how it exactly works, you can let me know.
Also this search is case sensitiv. In the textfile you have quite a mess of uppercase and lowercase. Maybe address that if you want to simplify the use of your programm a bit.

def tickers_to_dict():
ticker_dict = {}
bestand = open('pe_8_4_tickers.txt', 'r')
tickers = bestand.readlines()
for line in tickers:
k, v = line.split(':')
ticker_dict[k] = v
return (ticker_dict)
def name_to_symbol(mydict):
given_input = input("Enter company name: ")
for key, value in mydict.items():
if given_input == key:
print("Ticker symbol:", value)
return
else:
# print("Ticker symbol: )
# except:
print("False Input")
def symbol_to_name(mydict):
given_input = input("Enter ticker symbol: ")
for key, value in mydict.items():
if given_input == value:
print("Ticker symbol:", key)
return
else:
print("False Input")
name_to_symbol(tickers_to_dict())
symbol_to_name(tickers_to_dict())
Athos it didnt work
second def statement returns with false input

Related

Data Structure Option

I'm wondering what appropriate data structure I'm going to use to store information about chemical elements that I have in a text file. My program should
read and process input from the user. If the user enters an integer then it program
should display the symbol and name of the element with the number of protons
entered. If the user enters a string then my program should display the number
of protons for the element with that name or symbol.
The text file is formatted as below
# element.txt
1,H,Hydrogen
2,He,Helium
3,Li,Lithium
4,Be,Beryllium
...
I thought of dictionary but figured that mapping a string to a list can be tricky as my program would respond based on whether the user provides an integer or a string.
You shouldn't be worried about the "performance" of looking for an element:
There are no more than 200 elements, which is a small number for a computer;
Since the program interacts with a human user, the human will be orders of magnitude slower than the computer anyway.
Option 1: pandas.DataFrame
Hence I suggest a simple pandas DataFrame:
import pandas as pd
df = pd.read_csv('element.txt')
df.columns = ['Number', 'Symbol', 'Name']
def get_column_and_key(s):
s = s.strip()
try:
k = int(s)
return 'Number', k
except ValueError:
if len(s) <= 2:
return 'Symbol', s
else:
return 'Name', s
def find_element(s):
column, key = get_column_and_key(s)
return df[df[column] == key]
def play():
keep_going = True
while keep_going:
s = input('>>>> ')
if s[0] == 'q':
keep_going = False
else:
print(find_element(s))
if __name__ == '__main__':
play()
See also:
Finding elements in a pandas dataframe
Option 2: three redundant dicts
One of python's most used data structures is dict. Here we have three different possible keys, so we'll use three dict.
import csv
with open('element.txt', 'r') as f:
data = csv.reader(f)
elements_by_num = {}
elements_by_symbol = {}
elements_by_name = {}
for row in data:
num, symbol, name = int(row[0]), row[1], row[2]
elements_by_num[num] = num, symbol, name
elements_by_symbol[symbol] = num, symbol, name
elements_by_name[name] = num, symbol, name
def get_dict_and_key(s):
s = s.strip()
try:
k = int(s)
return elements_by_num, k
except ValueError:
if len(s) <= 2:
return elements_by_symbol, s
else:
return elements_by_name, s
def find_element(s):
d, key = get_dict_and_key(s)
return d[key]
def play():
keep_going = True
while keep_going:
s = input('>>>> ')
if s[0] == 'q':
keep_going = False
else:
print(find_element(s))
if __name__ == '__main__':
play()
You are right that it is tricky. However, I suggest you just make three dictionaries. You certainly can just store the data in a 2d list, but that'd be way harder to make and access than using three dicts. If you desire, you can join the three dicts into one. I personally wouldn't, but the final choice is always up to you.
weight = {1: ("H", "Hydrogen"), 2: ...}
symbol = {"H": (1, "Hydrogen"), "He": ...}
name = {"Hydrogen": (1, "H"), "Helium": ...}
If you want to get into databases and some QLs, I suggest looking into sqlite3. It's a classic, thus it's well documented.

list of lists to find an element from user input

right now, I'm trying to do a simple program, where user can add new, view, search, and delete. But as for now, I'm stuck at def findEmp(): below is my code and I'm really appreciate for you guys to help me with this problem.
When I key in the existing name 'mia' from global list, the result show 'Employee name not exist'.
from tabulate import tabulate
emps_global = [['mia','hr','admin']] # existing element
tablehead = ['Name', 'Department', 'Position']
def addnew():
emp_new = [] # empty local list
emp_new.append(input("Enter name: "))
emp_new.append(input("Enter department: "))
emp_new.append(input("Enter position: "))
emps_global.append(emp_new) # append local list to global list called emps_global
print(emps_global) # print out list of lists for emps_global
def findEmp():
emp = input("Enter employee name: ") # even existing name in the global list show 'not exist'
if emp in range(len(emps_global)): # i'm not sure this is correct or not
print("Yes employee exist")
elif emp not in range(len(emps_global)):
print("Employee name not exist")
def view():
print(tabulate(emps_global, headers=tablehead, tablefmt='psql'))
def deleteInfo():
pass
while True:
print("[1] to add")
print("[2] to search")
print("[3] to view")
print("[4] to delete")
inp = input(">> ")
if inp == '1':
addnew()
elif inp == '2':
findEmp()
elif inp == '3':
view()
elif inp == '4':
deleteInfo()
else:
print("Wrong input")
Edit you findEmp() as
def findEmp():
emp = input("Enter employee name: ") # even existing name in the global list show 'not exist'
for entry in emps_global:
if entry[0]==emp: # i'm sure this is correct or not
return entry
return "Name does not exist"
the range(len(emp_globs)) gives a list of numbers from 0 to len(emp_globs), so your condition compares the input name with a number, hence it doesn't work.

Problem retrieving individual objects in pickled dictionary (Python 3)

My program stores "food" objects that are pickled into a dictionary and stored in a csv file, which acts as a database. I want to retrieve individual food objects on command from the dictionary, but when I attempt to I seem to only retrieve the last object in the dictionary.
import pickle
class Food(object):
fooddict = dict({})
def __init__(self, name, weight, calories, time):
self.name = name
self.weight = weight
self.calories = calories
self.time = time
def __str__(self):
return '{self.name}s'.format(self=self) + \
' weigh {self.weight}'.format(self=self) + \
' ounces, contain {self.calories}'.format(self=self) + \
' calories, and stay fresh for {self.time}'.format(self=self) + \
' days.'
#classmethod
def createFoodInput(cls):
name = str(input("Enter the name: "))
weight = float(input("Enter the weight: "))
calories = float(input("Enter the calories: "))
time = float(input("Enter how many days it can store for: "))
return cls(name, weight, calories, time)
def storeFoodDict(f):
fooddict = Food.retreiveFoodDict()
if fooddict == "Empty File":
fooddict = dict({f.name: f})
with open("food.csv", 'wb') as filewriter:
try:
pickle.dump(fooddict, filewriter)
except:
print("Error storing pickled dictionary")
else:
food_found = False
for key in list(fooddict):
if key.__eq__(f.name):
print("Food already stored!")
food_found = True
if not food_found:
fooddict.update({f.name: f})
with open("food.csv", 'wb') as filewriter:
try:
pickle.dump(fooddict, filewriter)
except:
print("Error storing pickled dictionary")
#classmethod
def retreiveFoodDict(cls):
with open("food.csv", 'rb') as filereader:
try:
fooddict = pickle.load(filereader)
return fooddict
except EOFError:
return("Empty File")
def findFood(title):
fooddict = Food.retreiveFoodDict()
for key in list(fooddict):
if key.__eq__(title):
continue
return fooddict[key]
s = "apple"
n = findFood(s) #does not work, it returns banana instead of apple
#which is really just grabbing whatever is the
#last object in the dictionary
m = findFood("banana") #seems to work, but only because banana is the
#last object in the dictionary
print(n) #should print an apple "food object" but instead prints a banana
print(str(m.calories)) #works, but if I said n.calories it would still print
#m.calories instead
p = Food.retreiveFoodDict() #seems to work and retrieve the dictionary
print(str(p)) #also seems to work of course
Console Output:
bananas weigh 5.0 ounces, contain 120.0 calories, and stay fresh for 3.0 days.
120.0
{'apple': <main.Food object at 0x00D2C2E0>, 'banana': <main.Food object at 0x00D36D00>}
The dictionary contains 2 food objects (apple and banana), but the print(n) statement shows a banana, not an apple. Can anyone point out why this is or what I am misunderstanding? Thank you so much!
I found the answer to my own problem. I was misusing the continue in my findFood function.
This code solved my issues.
def getFood(food_name):
fooddict = Food.retreiveFoodDict()
for key in list(fooddict):
if key.__eq__(food_name):
return fooddict[key]
What this function does is simply retrieve a dictionary of objects in a csv file and iterates through the keys until the passed key name is located. If found, the proper key name will be returned as a food object. My original mistake was using the "continue" keyword to stop the for-loop, which was returning the object directly after the one we wanted.

Why do I keep getting the AttributeError: 'str' object has no attribute 'Student' when running my program

I am trying to run a program that implements Object Oriented Programming to help a student register for a course. I keep running into an Attribute Error and can't seem to figure out where my code went wrong.
I initially thought it had something to do with the fact that I had not implemented the self parameter in all the method def statements. But after I fixed this, I still encountered the same error message.
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
TRUE = True
FALSE = False
COURSES_INPUT = 'courses-sample.txt'
STUDENTS_INPUT= 'students-sample.txt'
import student
import course
def main():
process_students()
process_courses()
option = get_option()
while option != 5:
if option == 1:
course_num = input('please input course number of course you wish to add: ')
add_course = new_student.add_course(course_num)
while add_course == FALSE:
print('The course requested for add does not exist. Please Try Again.')
course_num = input('Please input course number of course you wish to add: ')
if new_course.space_available() == TRUE:
new_course.enroll_student()
else:
print('Class requested does not have any seats available.')
if option == 2:
course_num = input('please input course number of course you wish to drop: ')
drop_course = new_student.drop_course(course_num)
while drop_course == FALSE:
print('The enrolled course requested for drop does not exist. Please Try Again.')
course_num = input('Please input course number of course you wish to drop: ')
new_course.drop_student()
if option == 3:
print_student_info(student_dict)
if option == 4:
print_course_schedule(course_dict)
option = get_option()
write_updated('students-updated.txt',student_dict)
write_updated('courses-updated.txt',course_dict)
def print_menu():
print("1. Add course")
print("2. Drop course")
print("3. Print student's schedule")
print("4. Print course schedule")
print("5. Done")
print("")
def get_option():
print_menu()
choice = input("What would you like to do? ")
while choice not in range(1,6):
print_menu()
choice = input("Choice is invalid. What would you like to do? ")
return choice
def process_students():
student_dict = {}
student_info = open(STUDENTS_INPUT,"r")
for student in student_info:
info_list = student.split(":")
new_id = info_list[0]
first_name = info_list[1]
last_name = info_list[2]
course_list = info_list[3:]
new_student = student.Student(new_id, first_name, last_name, course_list)
print(new_student.line_for_file())
student_dict[new_eid] = new_student
student_info.close()
def process_courses():
course_dict = {}
course_info = open(COURSES_INPUT,"r")
for course in course_info:
info_list = course.split(";")
unique_num = info_list[0]
class_name = info_list[1]
prof = info_list[2]
seats = info_list[3]
capacity = info_list[4]
new_course = course.Course(unique_num, class_name, prof, seats, capacity)
course_dict[unique_num] = new_course
course_info.close()
def print_course_schedule(course_dict):
for value in course_dict:
print(value)
def print_student_info(student_dict):
for value in student_dict:
print(value)
def get_id():
eid = input("What is the UT EID? ")
while eid not in student_dict:
eid = input("Invalid UT EID. Please re-enter: ")
return eid
def get_unique():
unique = input("What is the course unique number? ")
while unique not in course_dict:
unique = input("Invalid unique number. Please re-enter: ")
return unique
def write_updated(filename,dictionary):
output_file = open(filename,'w')
for key in dictionary:
output_file.write(dictionary[key])
output_file.close()
main()
Error Message:
Traceback (most recent call last):
File "C:\Users\njung\Downloads\MIS 304 Final Project\untitled folder\Nguyen_Calvin_Jung_Nicholas-FP.py", line 132, in <module>
main()
File "C:\Users\njung\Downloads\MIS 304 Final Project\untitled folder\Nguyen_Calvin_Jung_Nicholas-FP.py", line 24, in main
process_students()
File "C:\Users\njung\Downloads\MIS 304 Final Project\untitled folder\Nguyen_Calvin_Jung_Nicholas-FP.py", line 83, in process_students
new_student = student.Student(new_id, first_name, last_name, course_list)
AttributeError: 'str' object has no attribute 'Student'
>>>
I also have the classes used stored in separate files (was required for the program) and have imported the modules containing these classes into main as you can see at the top.
Your error is AttributeError: 'str' object has no attribute 'Student'
Looking at the trace, it seems that it originates from this code:
student_info = open(STUDENTS_INPUT,"r")
for student in student_info:
info_list = student.split(":")
new_id = info_list[0]
first_name = info_list[1]
last_name = info_list[2]
course_list = info_list[3:]
new_student = student.Student(new_id, first_name, last_name, course_list)
Here you've opened a file. student_info is the file, and you iterate over the lines in the file. Each line student is a string.
You later call student.Student(new_id, first_name, last_name, course_list), but since student is just a string, it naturally does not contain a Student method.

When I use string,find[::] in another def, the string.find() says it's attribution doesn't work

When i use find() like string.find[::] in another def function, it says that says attribution error. Why does it not work?
def parts(phrase):
space=phrase.find(' ')
first_word=phrase[0:space]
return first_word
def rest_of_phrase(phrase):
space=phrase.find(' ')
rest_of_phrase=phrase[space+1:]
return rest_of_phrase
def jesus_this_part_is_hard(first_word,rest_of_phrase):
total_num=len(rest_of_phrase)
count=0
savepoint=[]
while total_num<count:
for i in total_num:
if i==' ':
savepoint+=[i]
count+=1
print(first_word," ")
x=savepoint[::-1]
for i in x:
if i==x[0]:
print(rest_of_phrase[i:]," ")
p=i
elif i!=x[0]:
print(rest_of_phrase[i:p],"")
p=i
def main():
phrase = input("Enter the phrase")
parts(phrase)
parts(rest_of_phrase)
jesus_this_part_is_hard(first_word,rest_of_phrase)
The result that I got was line 2, in parts
space=phrase.find(' ')
AttributeError: 'function' object has no attribute 'find'
parts(rest_of_phrase) here rest_of_phrase is function hence you are seeing this error
replace your main function with below and it will fix syntax errors (Not sure about the logical errors)
def main()
phrase = input("Enter the phrase")
first_word = parts(phrase)
rest_of_phrase = rest_of_phrase(phrase)
jesus_this_part_is_hard(first_word,rest_of_phrase)

Resources