How to merge two dictionaries together and link them - python

Im doing an exercise where I have to ask for input of info and input of medical records, and I'm not sure how to "link" a medical record from one dictionary, to a patient of my other dictionary.
So far, I've got this.
For patient info:
info_patients = []
while True:
Name = input("Insert name: ")
Lastname = input("Insert last name: ")
Birth = input("Insert date of birth: ")
Nationality = input("Insert nationality:")
repeat = input("Do you need to add more data? (yes / no): ")
info_patients.append({
"Name": Name,
"Lastname": Lastname,
"Birth": Birth,
"Nationality": Nationality
})
if repeat == 'no' or repeat == 'NO':
break
print(info_patients)
For medical records:
med_record = []
while True:
Date = input("Insert date of treatment: ")
Reason = input("Insert reason of treatment: ")
Doctor = input("Insert doctor in charge of treatment: ")
Remark = input("Insert any remarks:")
repeat = input("Do you need to add more data? (yes / no): ")
med_record.append({
"Date": Date,
"Reason": Reason,
"Doctor": Doctor,
"Remark": Remark
})
if repeat == 'no' or repeat == 'NO':
break
print(med_record)
How can I make it so, by an user input, link a medical record from my last dict to a patient of my first dict?

Related

How to edit and delete keys and values in python dict

i have a little problem that needs solving,
i have to write a program that saves contacts in a dict and be able to
1- add new contacts
2- delete contacts
3- edit contacts
4- list contacts
5- show contacts
i wrote a simple program that saves contacts into a dictionary but i have a problem with the rest and i could really user some help!!
here is my code:
contacts = {"Mohamed": {"name": "Mohamed Sayed", "number": "017624857447", "birthday": "24.11.1996", "address": "Ginnheim 60487"},
"Ahmed": {"name": "Ahmed Sayed", "number": "0123456789", "birthday": "06.06.1995", "address": "India"}}
def add_contact():
for _ in range(0, 1):
contact = {}
name = input("Enter the name: ")
number = input("Enter the number: ")
birthday = input("Enter the birthday")
address = input("Enter the address")
contact["name"] = name
contact["number"] = number
contact["birthday"] = birthday
contact["address"] = address
print(contact)
contacts.update(contact)
add_contact()
print(contacts)
def del_contact():
user_input = input("Please enter the name of the contact you want to delete: ")
for k in contacts:
if user_input == contacts["name"]:
del contacts[k]
del_contact()
print(contacts)
def edit_contact():
user_input = input("please enter the contact you want to edit: ")
for k, v in contacts:
if user_input == contacts["name"]:
contacts.update(user_input)
def list_contact():
pass
def show_contact():
user_input = input("please enter the contact you want to show: ")
for k, v in contacts.items():
if user_input == contacts["name"]:
print(key, value)
show_contact()
For your def's you dont need to use a for ... in range(...) loop, rather you can just call upon that value by the value of user_value. I've decided to not include def edit_contact(): in this as it currently doesn't edit anything, all it does is add a new element within contacts with that in mind
contacts = {"Mohamed": {"name": "Mohamed Sayed", "number": "017624857447", "birthday": "24.11.1996", "address": "Ginnheim 60487"},
"Ahmed": {"name": "Ahmed Sayed", "number": "0123456789", "birthday": "06.06.1995", "address": "India"}}
def add_contact():
for _ in range(0, 1):
contact = {}
name = input("Enter the name: ")
number = input("Enter the number: ")
birthday = input("Enter the birthday")
address = input("Enter the address")
contact["name"] = name
contact["number"] = number
contact["birthday"] = birthday
contact["address"] = address
print(contact)
contacts[name] = contact
add_contact()
print(contacts)
def del_contact(contacts):
user_input = input("Please enter the name of the contact you want to delete: ")
contacts = contacts.pop(user_input)
del_contact(contacts)
print(contacts)
def edit_contact():
user_input = input("please enter the contact you want to edit: ")
for k, v in contacts:
if user_input == contacts["name"]:
contacts.update(user_input)
def list_contact():
pass
def show_contact():
user_input = input("please enter the contact you want to show: ")
print(contacts[user_input])
#you can use 'contacts[user_input]['name', 'number', 'birthday' or 'address']' to call upon specific elements within the list
show_contact()
Hope this helps.

Creating a function where I can input first names and last names into a dictionary

I am kind of stuck, I am trying to make a function that allows me to append onto an empty dict, I want to add first name and surname, and also make it possible to have people with same last names but different first names. Any ideas? This is my first time asking a question on here, let me know if I need to find any other info thanks!
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
people[key] = input('Please enter your {}: '.format(value))
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
people()
First ask the user the input('Please enter your {}: '.format(value))
store it in a variable and then assign the people[key] to the variable
Example:
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people[key] = name
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
As mentioned in the comments that the people dicts gets reset
So with the approach of nested dicts you can use this:
def people():
people_ = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
print(qs)
index = f"person_{len(people_) + 1}"
people_[index] = {}
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people_[index][key] = name
print(people_)
prompt = input("Another person? (Y/N): ")
print(people_)
return people_
def people():
people = {}
add_person_msg = "Add person to list? (Y/N): "
first_name_msg = "First name: "
last_name_msg = "Last name: "
while input(add_person_msg).lower() == 'y': #.lower()
people[input(first_name_msg)] = input(last_name_msg)
return people
print(people())
if you wanted to work with the names before storing in dictionary, for example capitalize them:
def people_dict():
fn_msg = "First name: "
ln_msg = "Last name: "
people = {}
while input("Add person? y/n: ").lower() == 'y':
fn, ln = input(fn_msg).title(), input(ln_msg).title()
people[fn] = ln
return people
Also instead of using .format() method,
input('Please enter your {}: '.format(value)
if you are using Python 3.5 and above you can use f-strings:
input(f'Please enter your {value}:')

How can I print a word from an array?

Im trying to print the email of the student, in the while loop at the bottom im also trying to input the students email but I cannot figure how to do it correctly.
Code:
array1 = []
numstudents = int(input("How many students are in the class?: "))
for i in range (numstudents):
studentname,studentemail,dayofbrith,monthofbrith,yearofbrith = input("Enter the student name, the
student's email and the date of birth in the form 'name, email, day of birth, month of birth, year
of birth' : ").split("")
array1.append(studentname+studentemail+dayofbrith+monthofbrith+yearofbrith)
if studentname == "stop":
print("")
break
else:
print("")
print(array1)
while True:
email = input("From which student's email you want: ")
if email any in array1[0]:
print("")
print(array1[1])
students = []
numstudents = int(input('How many students are in the class?: '))
for _ in range(numstudents):
print("Please enter the following: ")
print("The student's name, The student's email, day of birth, month of birth, year of birth")
students.append(input().split())
target = input("Which studen't email you want: ")
for i in students:
if i[0] == target:
print(f"The student's email is {i[1]}")
Try if this is what you want
Ah, definitely a problem for a dictionary.
dict1= {}
numstudents = int(input("How many students are in the class?: "))
for _ in range (numstudents): #As nk03 correctly points out - we don't need to carry the iterator, so can use an _ instead
studentname,studentemail,dayofbirth,monthofbirth,yearofbirth = input("Enter the student name, the student's email and the date of birth in the form 'name,email,day of birth,month of birth,year of birth' : ").split(",")
if studentname == "stop":
break
else:
dict1[studentname] = {'email':studentemail, 'dOB':dayofbirth, 'mOB':monthofbirth, 'yOB':yearofbirth}
while True:
name = input("From which student's email you want: ")
if name in dict1:
print(dict1[name]['email'])
else:
print(name + " not found in dict")

Is there anyway I can simplify my Python program? it runs but I feel like the implementation could be simpler

This program asks a user at a bank for 3 inputs their bank id number, first name, and last name. If the user input is not the same as the default user (Ryan)
then, the user is blocked from continuing, else they are welcomed.
Can I have a simpler implementation for this
f_name = input("What is your first name: ")
print("You entered:" + f_name)
f_name = f_name
l_name = input("What is your last name: ")
print("You entered:" + l_name)
l_name = l_name
bid = int(input("What is your bid: "))
print(f"You entered: {bid}")
bid = bid
if f_name == "Ryan" and l_name == "Monaghan" and bid == 12345:
print("Welcome, Ryan")
else:
print("Access Denied")
I am a big fan of loops and comparison on data objects instead of values specifically.
print('Please enter the following information:')
questions = [
'First name',
'Last name',
'Bid'
]
answers = []
for q in questions:
answers.append(input(q + ': '))
if answers == ['Ryan', 'Monaghan', '12345']:
print('Welcome, Ryan')
else:
print('Access Denied')
output:
Please enter the following information:
First name: Ryan
Last name: Monaghan
Bid: 12345
Welcome, Ryan
This is in response to a follow-up question as to how to provide a retry loop if the user input is rejected.
print('Please enter the following information:')
questions = [
'First name',
'Last name',
'Bid'
]
answers = []
while(True): # Loop indefinately
for q in questions:
answers.append(input(q + ': '))
if answers == ['Ryan', 'Monaghan', '12345']:
print('Welcome, Ryan')
break # Got a valid response, break out of the loop, note you may want to set a variable here as well to denote a successful response.
else:
print('Access Denied')
r = input('Would you like to retry? (y/n):').lower().strip()
if r != 'y' and r != 'yes':
break # user does not want to try again, break out of loop

Python dictionaries and formatting

I am trying to solve the same a problem that does the following...
Create a program that stores Employee objects in a dictionary. Use the employee ID number as the key. The program should present a menu that lets the user perform the following actions:
Look up an employee in the dictionary
Add a new employee to the dictionary
Change an existing employee’s name, department, and job title in the
dictionary
Delete an employee from the dictionary
Quit the program
When the program ends, it should pickle the dictionary and save it to a file. Each time the program starts, it should try to load the pickled dictionary from the file. If the file does not exist, the program should start with an empty dictionary.
I found another user that posted the question here but I am having some different problems.
How should I quit the program? I tried break but it failed
miserably.
I know my formatting is atrocious but I can't figure out where it is
going wrong.
Here is what I have so far:
def main():
if os.path.exists("employee.dat"):
file = open("employee.dat","rb")
employee_dictionary = pickle.load(file)
file.close()
else:
emp1 = Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = Employee("Joy Rogers", 81774, "Manufacturing", "Engineer")
employee_dictionary = {emp1.get_ID_number(): emp1.get_name()+ '' + emp1.get_dept()+ '' + emp1.get_job_title(),\
emp2.get_ID_number(): emp2.get_name()+ '' + emp2.get_dept()+ '' + emp2.get_job_title(),\
emp3.get_ID_number(): emp3.get_name()+ '' + emp3.get_dept()+ '' + emp3.get_job_title()}
#should I add another function here to call the employee_dictionary?
choice = 'y'
while choice.upper()== 'Y':
print("Make a selection from the following actions:")
print("Lookup an employee in the dictionary: 1")
print("Add a new employee to the dictionary: 2")
print("Change an existing employee's name, department, and job title in the dictionary: 3")
print("Delete an employee from the dictionary: 4")
print("Quit the program: 5")
selection = input("Make your selection: ")
if int(selection) == 1:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
print(employee_dictionary[int(id_number)])
else:
print("The employee does not exist.")
else:
if int(selection) == 2:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
print('That employee already exists.')
else:
name = input("Enter the name of the employee:")
dept = input("Enter the department of the employee:")
title = input("Enter the job title of the employee:")
emp4 = Employee(name,int(id_number), dept, title)
employee_dictionary[emp4.get_ID_number()]= emp1.get_name()+ '' + emp4.get_dept()+ '' + emp4.get_job_title()
print("The employee was added.")
else:
if int(selection) == 3:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
name = input("Enter the name of the employee:")
dept = input("Enter the department of the employee:")
title = input("Enter the job title of the employee:")
emp4 = Employee(name,int(id_number), dept, title)
employee_dictionary[emp4.get_ID_number()]= emp1.get_name()+ '' + emp4.get_dept()+ '' + emp4.get_job_title()
print("The employee record has been updated.")
else:
print("Record not found.")
else:
if int(selection) == 4:
id_number = input("What is the employee's ID number?")
print("Deleted: ", employee_dictionary.pop(int(id_number),"Record not found."))
else:
if int(selection)!=5:
print("")
#break
choice = input("Do you want to make another selection (y or n)?")
file = open('employee.dat','wb')
pickle.dump(employee_dictionary,file)
file.close()
main()

Categories