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.
Related
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?
New to programming and trying to learn how to store data using pickle. Essentially, what I'm trying to do is create an address book using classes stored in a dictionary. I define the class (Contact). It all worked, but when I tried to introduce pickling to store data from a previous session, I've created 2 errors that I've found so far.
1: If I select to load a previous address book, I cant update or view the class variables. It's almost like there are two different dictionaries.
2: I select not to load a previous address book and add a contact. When I add the contact and try to view the contacts, I'll get an "Unbound Error: local variable 'address book' referenced before assignment"
What am I doing wrong with pickling?
address_book= {}
class Contact:
def __init__(self,first_name,last_name, phone,company):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.company = company
def __call__(self):
print("Contact: %s \nPhone #: %s \nCompany: %s" %(self.name,self.phone,self.company))
def erase(entry):
del address_book[entry] # delete address book entry
del entry #delete class instance
def save():
new_file = open("addressBook.pkl", "wb")
saved_address = pickle.dump(address_book, new_file)
new_file.close()
def load():
open_file = open("addressBook.pkl", "rb")
address_book = pickle.load(open_file)
open_file.close()
print(address_book)
return address_book
def add_contact():
first_name = input("Please type the first name of the contact. ")
last_name = input("Please type in the last name of the contact. ")
if " " in first_name or " " in last_name:
print("Please do not add spaces to your first or last name.")
else:
phone = input("Please type the user phone number without hyphens. ")
if not phone.isnumeric():
print("That isn't a valid phone number.")
else:
company = input("Please type the company they work for. ")
contact = Contact(first_name,last_name,phone,company)
address_book[first_name + " " +last_name] = contact #assign key[first and last name] to value[the class instance] in dictionary
def view_contact(entry):
if entry in address_book:
print("First Name: %s" %(address_book[entry].first_name)) #get class variables
print("Last Name: %s" %(address_book[entry].last_name))
print("Phone Number: %s" %(address_book[entry].phone))
print("Company: %s" %(address_book[entry].company))
else:
print("That person isn't in your address book")
def update(entry):
if entry in address_book:
update_choice = input("Would you like to update the first name (f), last name (l), phone (p), or company (c)? ").lower()
if update_choice == "f":
address_book[entry].first_name = input("Please type the updated first name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry] #delete old key
elif update_choice == "l": #update last name
address_book[entry].last_name = input("Please type the updated last name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry]
elif update_choice == "p":
address_book[entry].phone = input("Please type the updated phone number of this contact. ")
elif update_choice == "c":
address_book[entry].company = input("Please type the updated company of this contact. ")
else:
print("That was not valid. Please try again.")
def main():
print("Welcome to your address book!!")
returning_user = input("Would you like to load a previous address book? Y or N ").lower()
if returning_user == "y":
address_book = load()
while True:
choice = input("Please type A:Add, B:View All Contacts, V:View a Contact, D:Delete, U:Update, or X:Exit ").lower()
if choice == "x":
break
elif choice == "a":
add_contact()
elif choice == "b":
if len(address_book) == 0: #error check if no contacts
print("You don't have any friends. PLease go make some and try again later. :(")
else:
for i in address_book:
print(i)
elif choice == "v":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
view = input("Who do you want to view? Please type in their first and last name. ")
view_contact(view)
elif choice == "d":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
contact = input("Please type the first and last name of the person you want to delete ")
if contact in address_book:
erase(contact)
elif choice == "u":
if len(address_book) == 0:
print ("C'mon, you don't know anyone yet. How about you make some friends first?")
else:
choice = input("What is the first and last name of the person you'd like to update? ")
update(choice)
else:
print("That was not valid. Please try again.")
print()
save_book = input("Would you like to save your book? Y or N ").lower()
if save_book == "y":
save()
print("Thanks for using the address book!")
main()
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}:')
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")
If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook