Simply question making phone dictionary
What I want to do is putting person's name and number and finding them in dictionary!
Examples what I want to do
Enter command (a, f, d, or q).: a
Enter new name................: Perry
Enter new phone number........: 229-449-9683
Enter command (a, f, d, or q).: f
Enter name to look up...:
I would like to find full name and number when I type
Phone dictionary code what I wrote so far:
phone_dict = {}
command = input('Enter command (a, f, d, or q).: ')
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
while True:
if command == 'a':
newname
newphone
phone_dict[newname] = newphone
print(phone_dict)
# In here, 'while-loop' does not work.
In there, if I enter 'a' command, and type the name
The dictionary is supposed to be { Perry: 229-449-9683}
Thanks, The question might be little confused, but if you can help this out, I am very happy!
To find the result from the dictionary, you can loop through the items and check if the key contains the string you want to find. If you want to get all values which satisfy your query, you can create another list or dictionary and store the items you find:
phone_dict = {
"Han Perry": "1234",
"Harry Gildong": "2345",
"Hanny Test": "123",
}
find_str = "Han"
result = {}
for key, value in phone_dict.items():
# Converting it to lower makes it case insensitive
if find_str.lower().strip() in key.lower():
result[key] = value
print(result)
# {'Han Perry': '1234', 'Hanny Test': '123'}
Take note that this will run through all of the values of the dictionary: O(n)
To find the number using the first o last name of the person you could do:
a = 'Add a new phone number'
d = 'Delete a phone number'
f = 'Find a phone number'
q = 'Quit'
phone_dict = {}
while True:
# Gets the user command every loop
command = input('Enter command (a, f, d, or q).: ')
# Add a new registry to the directory
if command == 'a':
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
phone_dict[newname] = newphone
print(phone_dict)
# Find a registry on the directory
elif command == "f"
query = input("Enter name to look up...: ")
match = None
for key in phone_dict.keys():
if query.strip() in key:
match = phone_dict[key]
break
if match is None:
print(f"The name {query} could not be found on the directory")
else:
print(f"The phone number of {query} is {match}")
elif command == "d":
# Delete registry
elif command == "q":
# Quits program
else:
print(f"The command {command} was not found, please try again!")
In this case, I am using query.strip() to remove any extra start/end spaces that could cause to not find the person.
Related
im trying to code a simple contact book with just names and phone numbers. I want it to have the options add,remove,search and exit obviously. In my remove and search option i got one problem: For example if the use adds a new name to the contact book for example "Alex Balex" and wants to remove it or search it after he needs to type Alex Balex but i want the program to find and delete Alex out of the list if i search for "Alex Bal" aswell. That was my attempt but i cant find a solution:
import pickle
import sys
while True:
option = int(input(("You got 3 options 1=add 2=remove 3=search 4=exit and save. Please enter what you want to do: ")))
if option == 1:
names = []
names = pickle.load(open("names.dat", "rb"))
new_entry, new_number = str(input("Enter a new name which you want to be added to the CB in this format name:phone_number\nINPUT: ")).split(":")
new_user = "Name: " + new_entry + " Number: " + new_number
names.append(new_user)
pickle.dump(names, open("names.dat", "wb"))
elif option == 2:
names = []
names = pickle.load(open("names.dat", "rb"))
print(names)
new_removal = str(input("Enter what you want to remove: "))
for element in names:
if new_removal in element:
names.remove(names[names.index(element)])
pickle.dump(names, open("names.dat", "wb"))
elif option == 4:
sys.exit()
elif option == 3:
names = []
names = pickle.load(open("names.dat", "rb"))
print(names)
new_search = str(input("Search either a name or a number: "))
for element in names:
if new_search in element:
new_search = names[names.index(element)]
print(new_search)
pickle.dump(names, open("names.dat", "wb"))
A simple solution to your problem is to find the first name with the prefix the user entered, and then remove that:
elif option == 2:
new_removal = str(input("Enter what you want to remove: "))
i_remove = -1
for i, name in enumerate(names):
if name.lower()[0:len(new_removal)] == new_removal.lower():
i_remove = i
break
if i_remove != -1:
names.remove(i_remove)
else:
print(f"Name not found: {new_removal}", file=sys.stderr)
One question you'll need to consider though is what to do if multiple names start with the same prefix.
For example, what if a user's contact list contains Alex Balex, and Alex Ball, and the user asks to remove Alex Bal?
The simplest solution here would be to simply not remove anything since the specific name of the contact cannot be deduced - but another option might be instead to prompt the user with the list of contacts with that prefix and ask them to choose which one they want to remove.
I leave this part to you - good luck!
in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')
So my code outputs the value if the keys are found inside a dictionary using a userInput. I want to print out a message saying "Disease name does not exist" if the userInput is not found in the keys of the dictionary. I can get it to work, however, it goes through the wholeee list and repeats "Disease does not exist" for every line of the text.txt
I can't figure out how to make it just print once. Here is my code:
# Complete this function to meet its specifications.
# Begin with an empty dictionary, fill it, and return it.
def disease_to_code_dictionary( ) :
""" Function returns a dictionary with disease names as keys and
ICD 10 codes as values. """
diseases = {}
infile = open("ICD10.txt","r")
header_row = infile.readline() # skip the header row
for line in infile :
cells = line.split("\t") # split by the tab character
if len(cells) >= 2 : # only if the line had a tab
code = cells[0]
disease = cells[1]
disease = disease.lower() # lowercase
disease = disease.replace("\"","") # remove all double quotes
diseases[disease] = code
infile.close()
return diseases
# Complete this function to meet its specifications.
# The program should give the code if the disease name exists
# otherwise say "Disease name does not exist.".
def query_disease_to_code() :
""" Interactive function to query code from disease name. """
d = disease_to_code_dictionary() # disease to code dictionary
query = input("Give disease name (q to quit): ")
while query != "q" :
query = query.lower() # lowercase
# complete here
for key, value in d.items():
if query in key:
print(value)
else:
print("Disease name does not exist.")
query = input("Give disease name (q to quit): ")
query_disease_to_code()
I think instead of
for key, value in d.items():
if query in key:
print(value)
else:
print("Disease name does not exist.")
You could do
diseases = {'covid':'1223','flu':'1332'}
query = input("Choose your poison")
if query in diseases:
print(diseases[query])
else:
print("Disease name does not exist.")
or if you like one-liners
diseases = {'covid':'1223','flu':'1332'}
query = input("Choose your poison")
print (diseases[query] if query in diseases else "Disease Name does not Exist")
Found my solution:
d = disease_to_code_dictionary() # disease to code dictionary
query = input("Give disease name (q to quit): ")
while query != "q" :
query = query.lower() # lowercase
# complete here
for key, value in d.items():
if query == key:
print(value)
break
if query != key:
print("Disease name does not exist")
query = input("Give disease name (q to quit): ")
i think this might help you i proved it with this example diseasses={'name_1':'ICD_10_2','name_2':'ICD_10_2'}
while query != "q" :
query = query.lower() # lowercase
if query == "q":
break
if d.get(query)!= None:
print(d.get(query))
if d.get(query)== None:
print('Disease name does not exist.')
I'm new to programming, fyi. I want my program to restart back to the top based on what the user inputs. It will proceed if the user inputs 2 names. If they input 1 name or more than 2 names, it should restart the program but I'm not sure of how to do this.
def main():
print("Hello, please type a name.")
first_name, last_name = str(input("")).split()
while input != first_name + last_name:
print("Please enter your first name and last name.")
main()
You should use a while loop and check the length of the split before assigning:
def main():
while True:
inp = input("Please enter your first name and last name.")
spl = inp.split()
if len(spl) == 2: # if len is 2, we have two names
first_name, last_name = spl
return first_name, last_name # return or break and then do whatever with the first and last name
Use try/except
Well, your program didn't work for me to begin with, so to parse the first and last names simply, I suggest:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
Also your while loop will just, like, break your life if you run it without good 'ol ctrl+c on hand. So, I suggest:
def main():
print “type your first & last name”
try:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
if f and l:
return f + ‘ ‘+ l
except:
main()
The except: main() will re-run the program for you on error.
I'm trying to do a question out of my book and it asks:
Implement function names that takes no input and repeatedly asks the
user to enter a student's first name. When the user enters a blank
string, the function should print for every name, the number of
students with that name.
Example usage:
Usage:
names()
Enter next name: Valerie
Enter next name: Bob
Enter next name: Valerie
Enter next name: John
Enter next name: Amelia
Enter next name: Bob
Enter next name:
There is 1 student named Amelia
There are 2 students named Bob
There is 1 student named John
There are 2 students named Valerie
So far I have this code:
def names():
names = []
namecount = {a:name.count(a) for a in names}
while input != (''):
name = input('Enter next name: ')
names = name
if input == ('')
for x in names.split():
print ('There is', x ,'named', names[x])
I'm really lost here and any input would help out tons. Also if possible please explain how to fix my code
There are a lot of issues with namings in your function, you are using such variables like 'names' that is used for function name as well as 'input' that is a python function name for reading user input - so you have to avoid using this. Also you defining a namecount variable as a dict and trying to initialize it before fill. So try to check solution below:
def myFunc():
names = []
name = ''
while True: #bad stuff you can think on your own condition
name = raw_input('press space(or Q) to exit or enter next name: ')
if name.strip() in ('', 'q', 'Q'):
for x in set(names):
print '{0} is mentioned {1} times'.format(x, names.count(x))
break
else:
names.append(name)
myFunc()
OR:
from collections import defaultdict
def myFunc():
names = defaultdict(int)
name = ''
while True: #bad stuff you can think on your own condition
name = raw_input('press space(or Q) to exit or enter next name: ')
if name.strip() in ('', 'q', 'Q'):
for x in set(names):
print '{0} is mentioned {1} times'.format(x, names[x])
break
else:
names[name] += 1
I rewrote your function for you:
def names():
names = {} # Creates an empty dictionary called names
name = 'cabbage' # Creates a variable, name, so when we do our while loop,
# it won't immediately break
# It can be anything really. I just like to use cabbage
while name != '': # While name is not an empty string
name = input('Enter a name! ') # We get an input
if name in names: # Checks to see if the name is already in the dictionary
names[name] += 1 # Adds one to the value
else: # Otherwise
names[name] = 1 # We add a new key/value to the dictionary
del names[''] # Deleted the key '' from the dictionary
for i in names: # For every key in the dictionary
if names[i] > 1: # Checks to see if the value is greater for 1. Just for the grammar :D
print("There are", names[i], "students named", i) # Prints your expected output
else: # This runs if the value is 1
print("There is", names[i], "student named", i) # Prints your expected output
When doing names():
Enter a name! bob
Enter a name! bill
Enter a name! ben
Enter a name! bob
Enter a name! bill
Enter a name! bob
Enter a name!
There are 3 students named bob
There are 2 students named bill
There is 1 student named ben
Let's analyse your code:
def names():
names = []
namecount = {a:name.count(a) for a in names}
while input != (''):
name = input('Enter next name: ')
names = name
if input == ('')
for x in names.split():
print ('There is', x ,'named', names[x])
There seem to be a few problems, let's list them
The while loop's conditional
What you want to do check if input from user is '' (nothing)..
input is a built-in function for getting input from user, so it never will be ('').
The names = name statement
What you want to do is add name to the list names.
Here you are changing names to a string, which isn't what you want.
The if's conditional
same as 1.
The for loop
let's ignore.. just not valid.. here..
We fix these problems as follows(solution has same numbering as problem above that it solves)
Change the conditional to something like name != ''.
Also, before the loop begins, you need to get input once for this to work, which in this case has a bonus, the first input can have a different prompt.
Use names.append(name) to add name to names.
Same as 1.
Just look at the for loop below...
Try this
def names():
names = []
name = input('Enter a name: ').strip() # get first name
while name != '':
names.append(name)
name = raw_input('Enter next name: ').strip() # get next name
for n in set(names): # in a set, no values are repeated
print '%s is mentioned %s times' % (n, names.count(n)) # print output
def names():
counters = {}
while True:
name = input('Enter next name:')
if name == ' ':
break
if name in counters:
counters[name] += 1
else:
counters[name] = 1
for name in counters:
if counters[name] == 1:
print('There is {} student named {}'.format(counters[name],name))
else:
print('There are {} student named {}'.format(counters[name],name))
names()