I need assistance with my dictionary program in python - python

ok so.. i'm trying to write a program that creates a dictionary of son:father entries and another dictionary that contains father:son entries. The program must present the user a menu with five options.
text file is this: john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasaen:zade, david:dieter, adamLseth, seth:enos
Problem Statement:
Write a program that creates a dictionary of son:father entries and another dictionary that contains father:son entries. Your program must present the user a menu with five options. The following is an example only:
Father/Son Finder
0 – Quit
1 – Find a Father
2 – Find a Grandfather
3 – Find a Son
4 – Find a Grandson
Option 0 ends the program.
Option 1 prompts the user for the name of a son. If the dictionary contains the son:father pair, the program displays the father. Otherwise, the program should tell the user it does not know who the father is.
Option 2 prompts the user for the name of a grandson. If the dictionary contains enough information, the program displays the grandfather. Otherwise, the program should tell the user it does not know who the grandfather is.
Option 3 prompts the user for the name of a father. If the dictionary contains the son:father pair, the program displays the son. Otherwise, the program should tell the user it does not know who the son is.
Option 4 prompts the user for the name of a grandfather. If the dictionary contains enough information, the program displays the grandson. Otherwise, the program should tell the user it does not know who the grandson is.
The program must create the dictionary structure and populate it from data contained in a file provided to you. In addition, the program must continue to ask the user for a menu choice until the user chooses to quit.
I have this thus far. I haven't gotten very far in it...
sons_fathers = {}
fathers_sons = {}
#open filename: names.dat
fo = open("names.dat", "r")
data = fo.read()
print (data)
for line in fo:
here is the flow chart: ![Flow chart][1]
https://jsu.blackboard.com/bbcswebdav/pid-2384378-dt-content-rid-3427920_1/xid-3427920_1
Thanks for the help. I need it lol.

Let's hope nobody give you an exact solution to this homework.
Here some hints, you need to know what you can do with string, string.split() will help you a lot. Also, read about what you can do with dictionary. You will also need the raw_input function
The rest is simple programming. Good luck.

How you describe your solution, I don't think a dictionary is what you want for this.
The keys must be unique.
# wont work, keys aren't unique
father_son = {'danny':'brett', 'danny':'issak', 'danny':'jack'}
You could however try a dictionary with a list as the value:
father_son = {'danny':['brett','issak', 'jack']}
if 'danny' in father_son.keys() and 'brett' in father_son['danny']:
#do something
Or you could use a list of 2-tuples that stores the pairs:
father_son = [('danny', 'brett'), ('danny', 'issak'), ('danny', 'jack')]
if ('danny', 'brett') in father_son:
#do something

sons_fathers = {} # one father per son
fathers_sons = {} # one or many sons per father, use list or
# set for the values
with open("names.dat", "r") as fo: # use context manager to close file automatically
for line in fo: # ?? is there only one line, or one pair per line??
# do something with line
# assume you extracted "son" and "father"
sons_fathers[son] = father
if father in fathers_sons:
fathers_sons[father].add(son)
else:
fathers_sons[father] = {son}

Related

delete only 1 instance of a string from a file

I have a file that looks like this:
1234:AnneShirly:anneshirley#seneca.ca:4:5\[SRT111,OPS105,OPS110,SPR100,ENG100\]
3217:Illyas:illay#seneca.ca:2:4\[SRT211,OPS225,SPR200,ENG200\]
1127:john Marcus:johnmarcus#seneca.ca:1:4\[SRT111,OPS105,SPR100,ENG100\]
0001:Amin Malik:amin_malik#seneca.ca:1:3\[OPS105,SPR100,ENG100\]
I want to be able to ask the user for an input(the student number at the beginning of each line) and then ask which course they want to delete(the course codes are the list). So the program would delete the course from the list in the student number without deleting other instances of the course. Cause other students have the same courses.
studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
f = file.readlines()
with open("studentDatabase.dat","w") as file:
for line in lines:
if line.find(course) == -1:
file.write(line)
This just deletes the whole line but I only want to delete the course
Welcome to the site. You have a little ways to go to make this work. It would be good if you put some additional effort in to this before asking somebody to code this up. Let me suggest a structure for you that perhaps you can work on/augment and then you can re-post if you get stuck by editing your question above and/or commenting back on this answer. Here is a framework that I suggest:
make a section of code to read in your whole .dat file into memory. I would suggest putting the data into a dictionary that looks like this:
data = {1001: (name, email, <whatever the digits stand for>, [SRT111, OPS333, ...],
1044: ( ... )}
basically a dictionary with the ID as the key and the rest in a tuple or list. Test that, make sure it works OK by inspecting a few values.
Make a little "control loop" that uses your input statements, and see if you can locate the "record" from your dictionary. Add some "if" logic to do "something" if the ID is not found or if the user enters something like "quit" to exit/break the loop. Test it to make sure it can find the ID's and then test it again to see that it can find the course in the list inside the tuple/list with the data. You probably need another "if" statement in there to "do something" if the course is not in the data element. Test it.
Make a little "helper function" that can re-write a data element with the course removed. A suggested signature would be:
def remove_course(data_element, course):
# make the new data element (name, ... , [reduced course list]
return new_data_element
Test it, make sure it works.
Put those pieces together and you should have the ingredients to change the dictionary by using the loop and function to put the new data element into the dictionary, over-writing the old one.
Write a widget to write the new .dat file from the dictionary in its entirety.
EDIT:
You can make the dictionary from a data file with something like this:
filename = 'student_data.dat'
data = {} # an empty dictionary to stuff the results in
# use a context manager to handle opening/closing the file...
with open(filename, 'r') as src:
# loop through the lines
for line in src:
# strip any whitespace from the end and tokenize the line by ":"
tokens = line.strip().split(':')
# check it... (remove later)
print(tokens)
# gather the pieces, make conversions as necessary...
stu_id = int(tokens[0])
name = tokens[1]
email = tokens[2]
some_number = int(tokens[3])
# splitting the number from the list of courses is a little complicated
# you *could* do this more elegantly with regex, but for your level,
# here is a simple way to find the "chop points" and split this up...
last_blobs = tokens[4].split('[')
course_count = int(last_blobs[0])
course_list = last_blobs[1][:-1] # everything except the last bracket
# split up the courses by comma
courses = course_list.split(',')
# now stuff that into the dictionary...
# a little sanity check:
if data.get(stu_id):
print(f'duplicate ID found: {stu_id}. OVERWRITING')
data[stu_id] = (name,
email,
some_number,
course_count,
courses)
for key, value in data.items():
print(key, value)
i got something for you. What you want to do is to find the student first and then delete the course: like this.
studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
f = file.readlines()
with open("studentDatabase.dat","w") as file:
for line in lines:
if studentid in line: # Check if it's the right sudent
line = line.replace(course, "") # replace course with nothing
file.write(line)
You want to check if we are looking at the correct student, then replace the line but without the course code. Hope you can find it useful.

Import and insert word in sequence in Python

I want to import and insert word in sequence and NOT RANDOMLY, each registration attempt uses a single username and stop until the registration is completed. Then logout and begin a new registration with the next username in the list if the REGISTRATION is FAILED, and skip if the REGISTRATION is SUCCEDED.
I'm really confused because I have no clue. I've tried this code but it chooses randomly and I have no idea how to use the "for loop"
import random
Copy = driver.find_element_by_xpath('XPATH')
Copy.click()
names = [
"Noah" ,"Liam" ,"William" ,"Anthony"
]
idx = random.randint(0, len(names) - 1)
print(f"Picked name: {names[idx]}")
Copy.send_keys(names[idx])
How can I make it choose the next word in sequence and NOT RANDOMLY
Any Help Please
I am going to assume that you are happy with what the code does, with exception that the names it picks are random. This narrows everything down to one line, and namely the one that picks names randomly:
idx = random.randint(0, len(names) - 1)
Simple enough, you want "the next word in sequence and NOT RANDOMLY":
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
If you take a look at the link I've provided, you can see that lists have a pop() method, returning and removing some element from the list. We want the first one so we will provide 0 as the argument for the pop method.
We modify the line to look something like this
name = names.pop(0)
Now you still want to have the for-loop that will loop over all of the actions including name picking so you encapsulate all of the code in a for-loop:
names = [
"Noah" ,"Liam" ,"William" ,"Anthony"
]
for i in range(len(names)):
# ...
Copy = driver.find_element_by_xpath('XPATH')
Copy.click()
name = names.pop(0)
print(f"Picked name: {name}")
Copy.send_keys(name)
# ...
You might notice that the names list is not inside the for-loop. That is because we don't want to reassign the list every time we try to use a new name.
If you're completely unsure how for-loops work or how to implement one yourself, you should probably start by reading about how they work.
https://docs.python.org/3/tutorial/controlflow.html?highlight=loop#for-statements
Last but not least you can see some # ... comments in my example indicating where the logic will probably go for the other part of your question: "Then logout and begin a new registration with the next username in the list if the REGISTRATION is FAILED, and skip if the REGISTRATION is SUCCEDED." I don't think we I can help you with that since there is simply not enough context or examples in your question.
Refer to this guide explaining how to ask a well formulated question so we can help you more next time.

how to make a program ignore everything but the key word in users input?

datadict = {}#open the file
with open('phoneproblemquery.txt') as file:
for line in file:
problem, answer = line.split('-')
problems = problem.strip().split(' ')
for item in problems:
datadict[item] = answer
user_problem = input('What is the problem?:')
print(datadict[user_problem])
The text-file contains something like this:
screen - replace screen.
if I were to run this program and enter in 'screen' the program will respond 'replace screen'. but, if I were to enter something like 'the screen'(not just 'screen' alone) the program will give a 'keyError' and won't work.
what would I need to do to if the user enters 'the screen' (instead of just 'screen') for the program to provide an output 'replace screen'. would I need to put the users answer into arrays? if so how?
Thanks!
update: 'the screen' was just an example. The user can enter in any
form of way i.e 'screen is...' the keyword is screen. I would want
the program to identify the key word from the users input and get
the response 'replace screen'. ... ;( desperate for an answer...
You want the program to pick keywords out of the user input and look for them in datadict. The difficulty with that is picking out keywords. A simple approach is to have regular expressions rather than simple keywords as the keys of your lookup dictionary. You will of course have to do the matching yourself: the dictionary lookup process won't do it for you.
import re
datadict = {}
#open the file
with open(r'phoneproblemquery.txt') as file:
for line in file:
problem, answer = line.split('-')
problems = problem.strip().split(' ')
for item in problems:
datadict[re.compile(fr'{item}', re.IGNORECASE)] = answer
user_problem = input('What is the problem?:')
for regex, diagnosis in datadict.items():
if regex.search(user_problem):
print (diagnosis)
This will work, but in a more sophisticated implementation it might be better to put the regular expressions in the input data, rather than constructing them at runtime like I have done here. You are already allowing for something of the sort by having a space-delimited list if keywords in your input data. If you had regular expressions in the input instead, the same would apply, only instead of, say
keyboard kybd - replace keyboard
you would have
keyboard|kybd - replace keyboard
and in that event maybe a hyphen would not be the best delimiter. A carriage return might be better, since that can never appear in the input.

Append to list won't keep the last input on program restart?

I am trying to learn Python by doing.
Aim of the code below: To form a part of a larger file in which I will be checking if all info i.e. Address, email add, contact person etc is updated in a list (I am not sure whether to use lists, arrays or dictionary?). If yes I want it to give options to do various things for the customer etc.
The code below is basically checking whether a customer exists in the list. If not, it is supposed to add the customer name in c to the list.
When I run the program it works. But as soon as I restart the program the last added, i.e. if I entered the customer as: ABC in the last run of the program, is not in the list.
Can someone point me in the right direction on this? Also can I pass the values in the list onto multiple dictionaries as keys for further values to be added i.e. email address etc?
customer = ['GMS']
print ("Enter Customer Name:")
c = input()
if c in customer:
print ("Customer Exsists")
else:
customer.append(c)
print ("Added to list")
Your program is fine as far as it goes. It does input, and it does
append to the list.
However, all the data in the program will go away as soon as the program
exits. The only way to retain information across runs is to save the
information in some kind of persistent storage. As Rok Novosel mentions
in the comment, this can be done with the pickle module, though as a
beginner, you might want to defer that until later.
At this stage of your learning, I’d recommend looking at file
operations: opening and closing, reading and writing. For a single list
like this, the writelines() and readlines() file methods would be
the simplest way to save and restore, respectively.
As for your dictionary question: yes, since you’re making sure the
customer names are unique, you can use them as dictionary keys. Storing
that data would be more complicated; you could use pickle, or work out
a file structure to parse on input.
Q1: Your data resides in memory during one execution instance. When the program exits, the memory is freed and your data is not automatically stored elsewhere. You may use a format you like to store it onto the disk where data is persistent. Simply writing to a file could work for you at this moment of your learning.
Q2: Yes, you may use a dictionary.
Open file and read it in list
with open('file', 'r') as f:
customers = list(f)
f.close()
Do whatever You want to list. Then write to file.
To persist customers on HDD.
with open('file', 'w') as f:
for l in f:
f.write(str(l) + '\n')
f.close()

How would I save the data to a .csv file

I have made a program based on a maths quiz and have saved the data of the files to a .txt file. If I wanted to save the files in a .csv file would i just chnage .txt to .csv? Here is my code :
import time
import math
import random#I am using this to allow me to randomly pick the symbol operation and to randomly generate numbers
print("Title:Arithmetic Quiz")#Tells the user what the program is.
print("*************************************************************")#This is a line to make the presentation clearer to the user.
#The code below shows the user an introduction of what the program is about.
print("This program will ask you to complete the arithmetic quiz.")
print("The program has 10 questions. You will recieve feedback after.")
print("____________________________________________________________")
#The line above prints a line across the page.
while True:#This creates an infinity loop
UserName = input("What is your name?:")#Ask the user for there name.
if not UserName.isalpha():#This is used to check if the user name is anything else apart from alphabetical letters.
print("Error!Please enter your name using letters. ") #warning if wrong if wrong input given
continue#Continues with the code when correct input given.
else:#It breaks out of the while loop and proceeds with the quiz
break
ClassSelection= input("Please enter what Class you are in?:1, 2 or 3")
ClassChosen=0
while ClassChosen==0:
if ClassSelection=="1":
ClassChosen=1
elif ClassSelection=="2":
ClassChosen=1
elif ClassSelection=="3":
ClassChosen=1
else:
print("You must write 1, 2, or 3.")
ClassSelection=input("Enter the class you are in")
print(UserName," welcome to the Arithmetic Quiz.")#Welcomes the user to the quiz.
print("____________________________________________")
print("The quiz will begin in 3 seconds")
time.sleep(2)
for i in range(0,3):# range between
print (3 - i)#counts down by one
time.sleep(1)#Delays for 1 second
print("Begin!")
print("*****************************************")
RecentStudent= [0,0,0]#This is a list with dummy values. The use of this is to save the last three score of the user.
def MathsQuiz():#I have used a function to make my code more efficient.
score=0#No questions have been answered correctly yet so score is set to zero
for questionNum in range(10):#I have used this to allow me to set my Parameters.
Num1= random.randint (1, 10)#Generates a random number between 1 and 10 for Num1.
Num2= random.randint (1, 10)#Generates a random number between 1 and 10 for Num2
Symbol = ["+","-","*"]#These are my operators used for the arithmetic of Num1 and Num2.
Operation = random.choice(Symbol)#This will randomly choose a operating symbol for a question
RealAnswer= int(eval(str(Num1)+Operation+str(Num2)))#This is used to work out the answer for the question.The evaluate is used to interpret the code as a str and calculate an answer.
#It will store the value of the Answer and call it when it is needed.
print("Please give an answer for:", Num1, Operation, Num2)#This is what makes the question and outputs it to the user by using the random functions.
UserAnswer = int(input("Enter your answer here:"))#This asks the user to enter their anser to the question.
if UserAnswer == RealAnswer:#This checks if the answer from the user is the same as the real answer.
score = score + 1#If the user gets the question right 1 should be added to the score.
print("You are correct! :D")#The program will congratulate the user.
print("_______________________________________________")
else:#If the users answer is not the same as the real answer then it will print a wrong message.
print("You are incorrect! :( ")#This tells the user that they got the question incorrect and tells the user the real answer.
print("The answer was", RealAnswer)
print("________________________________________________")#This will be used to split the quiz.
print()#This is used to format the quiz.
print("__________________________________________________")
print("Thank you for completing the quiz!")
print("Your Score is loading")
import time
time.sleep(2)
print(UserName,"In this test you achieved",score,"/10")#This tells the user the score they achieved in the maths test.
print()#This is used to format the code
del RecentStudent[0]
RecentStudent.append(score)
print("Your three most recent scores are:",RecentStudent)
print("********************************************************")
def Resit1():#This function is used to easily call place of the program such as in this case when resitting.
Resit1=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit1== "Yes" or Resit1=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
#It tells the user that they are finished
def Resit2():#This function is used to easily call place of the program such as in this case when resitting.
Resit2=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit2== "Yes" or Resit2=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
print("Quiz Finished")#It tells the user that they are finished
MathsQuiz()#This will call the first function that has been set in the program.
Resit1()#This will call the Resit1 function when it is needed by the program.
Resit2()#This will call the Resit2 function when it is needed by the program.
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class1Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class1))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
elif ClassSelection=="2":#used to identify whether the ClassSelection is equal to 1.
Class2=[]#classA list is created and is empty.
Class2.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class2.append(UserName)#The name variable is appended as the second item.
Class2.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class2.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class2Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class2))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
elif ClassSelection==3:
Class3 = []#classA list is created and is empty.
Class3.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class3.append(UserName)#The name variable is appended as the second item.
Class3.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class3.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class3Scores.txt", 'a')#File opened called class3Scores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class3))#Allows me to write the class3 list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
This is my code would I need to change the bottom of the code to save the files in a .csv file. I tried doing a different method, but never got anywhere .
I suggest using the csv module. I've adapted your code to use it (there are a lot of ways you could make your life easier with your code, but let's focus on one issue at a time):
import csv
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
with open('Class1Scores.csv', 'wb') as file:
writer = csv.writer(file)
writer.writerow(str(Class1))
writer.writerow("\n")
Gentle into to the csv module
Because we're using the with keyword, there is no need to call file.close()
For a more advanced way of doing this, you could use pandas to_csv
Looks like your Class1 is simply a list. Then you can say file.write(",".join(Class1)). But a more robust method is to use the csv module - https://docs.python.org/2/library/csv.html

Categories