"Create a dictionary whose keys are names and whose value for a key is a favorite food of the person with that name as follows:
- The program should prompt for a name and favorite food and keep inputting names and favorite foods until the user enters an empty string for the name."
So far I have:
mydict=dict()
def favorite_food_name():
name=input(str("name:"))
food=input(str("food:"))
mydict[name]=food
print(mydict)
favorite_food_name()
But I can't get the code to repeat in any kind of loop. What kind of loop would you use?
Use While True loop, and test value of name after its input.
By the way, some tips when coding:
you do not need str("name:"), since "name:" is str
if not necessary, put mydict in the function part, use return statement, do not use it as model level
you can do more to validate the input, here I call a strip function to remove typo of input.
Here is a sample code:
def favorite_food_name():
mydict = dict()
while True:
name = input("name:")
name = name.strip()
if name == '':
break
food = input("food:")
food = food.strip()
mydict[name] = food
# print(mydict)
return mydict
if __name__ == '__main__':
mydict = favorite_food_name()
print(mydict)
Related
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')
Edit: changing code as the issue came up first somewhere else in my code
I'm trying to figure out how to use my dictionary from one function in another one and the other answers on here haven't helped.
The overall goal is to print the key and value just entered into the dictionary named contacts but contacts can only be defined inside init_phonebook
def init_phonebook():
contacts = {}
while True:
choice = print_menu()
if choice == 1:
list_contacts(contacts)
elif choice == 2:
add_contact(contacts)
elif choice == 3:
find_contact(contacts)
elif choice == 4:
edit_contact(contacts)
elif choice == 5:
delete_contact(contacts)
elif choice == 6:
delete_all(contacts)
elif choice == 7:
thanks()
Down here the issue is that .keys and .values don't work as it's not recognizing contacts as a dictionary. I've tried changing the parameter to something else but it doesn't work that way either.
def add_contact(contacts):
phone_number = input('Please enter a phone number: ')
name = input('What would you like to save the name as?: ')
if name in contacts:
print('This contact already exists in your phonebook')
elif name not in contacts:
contacts[name] = phone_number
print('Contact successfully saved')
print('Your updated phonebook is shown below')
for c in contacts:
print('{} --> {}'.format(contacts.keys(c), contacts.values(c)))
print()
the error message I get is:
File "c:\Users\myname\Desktop\VS Code Projects\contact_list.py", line 54, in add_contact
print('{} --> {}'.format(contacts.keys(c), contacts.values(c)))
TypeError: dict.keys() takes no arguments (1 given)
The problem is not how you go about passing the dictionary to these other functions.The error actually arising within your add_contact() function, due to how you are trying to iterate through the dictionary key-val pairs:
for c in contacts:
print('{} --> {}'.format(contacts.keys(c), contacts.values(c)))
It seems you want to iterate through the contacts. contact.keys() does not let you access/index a key, this method returns all of the keys in a dict. contact.values does not let you access/index a value, it returns all of the values in the dict. When you call "for c in contacts", c represents a key. So here are two alternative ways to iterate through:
Properly indexing on the contacts dict using the key c:
for c in contacts:
print('{} --> {}'.format(c, contacts[c]))
By iterating through both the key and value pairs:
for key,value in contacts.items():
print('{} --> {}'.format(key, value))
If confused about a type in Python, I recommend referring to the documentation!
dict.keys() and dict.values() both return arrays that can be indexed but accepts no inputs when called.
But in your case, since you are looping over the dictionary, each iteration stores the key in c. In your case that will be the name associated with the contact.
So you already have the key stored in c on each iteration. What you need next is to use the key to get the value like so dict[key] or dict.get(key).
Alternatively, you can loop over both keys and values simultaneously like so:
for name, phone_number in contacts:
print("{} ==> {}".format(name, phone_number))
I am altering your original code as follows:
def add_contact(contacts):
phone_number = input('Please enter a phone number: ')
name = input('What would you like to save the name as?: ')
if name in contacts:
print('This contact already exists in your phonebook')
else: #You seem to have only two options so no need for elif
contacts[name] = phone_number
print('Contact successfully saved')
print('Your updated phonebook is shown below')
for c in contacts: #c will hold name in each iteration
print('{} --> {}'.format(c, contacts[c]))
I have a dictionary that is similar to
my_dict ={'Bob' : 11, 'Sandy':12, 'Katy':13}
and I have a code that checks if the input matches the value
user_input = input('Enter a name')
while my_dict.get(user_input) == None:
chosenSchool = input('please enter a correct name')
and then other code happens
so that works out fine, but Im trying to have code commence if the user has typed the correct value from user_input, i tried something like this, and i made a list of both the keys and values from my_dict, person_name, and person_code.
if user_input.isdecimal():
while user_input not in my_dict.values():
chosenSchool = input("enter a correct name or number")
numval = int(user_input)
pos_of_Name = person_code.index[numval]
Name_person = person_name[pos_of_name]
So eventually the name of this person should be Name_person, and the code numval, but clearly I am doing something wrong. I could probably make a function or something as well
Ok so I am completely lost for this problem, please help me. I have already created a function that takes in a text file and sorts all the names into the text file, puts them in a dictionary. So my new dictionary looks like this:
namesDict = {'J': ['Jacob', 'Joshua'], 'T': ['Tyler'], 'A': ['Austin'], 'B': ['Brandon'], 'D': ['Daniel'], 'M': ['Michael', 'Matthew'], 'C': ['Christopher'], 'N': ['Nicholas']}
now I have to take in this dictionary I created and add new names. The new function has to do this
The function will ask the user to input their name. Assume the user will enter names with a capital first letter, and all lowercase letters after that.
If their name is already in the dictionary, print “[name] is already in the dictionary”, and then return the same dictionary.
If their name is not already in the dictionary, then you will add their name to the dictionary under the appropriate key, print “[name] added to dictionary”, and then return the updated dictionary.
If their name is not already in the dictionary AND the first letter of their name is not already a key in the dictionary, then you will add the first letter of their name as a key, with a list containing their name as the value. You will then print “[name] added to dictionary”, and return the updated dictionary.
so I have this so far which of course is not complete:
def updateDictionary(namesDict):
newname= input('What is your name?')
if newname = key:
print(newname'is already in the dictionary')
elif newname != key:
print (newname 'added to dictionary')
elif newname = key[0]:
print (newname 'added to dictionary')
also my first code to create the dictionary from the text file is this:
def newDictionary():
names={}
file = open('file.txt','r')
lines = file.read().split('\n')
if len(lines) == 1 and len(lines[0]) == 0:
print('empty file')
else:
for line in lines:
if line in names:
names[(line[0])].append(line)
else:
names[(line[0])] = [line,]
return names
but i am having an error in this code which says names[(line[0])] = [line,]
IndexError: string index out of range.
PLEASE PLEASE help me out. I don't know how to take in the new input name and put it in the dictionary.
Thank you
If you are getting IndexError for this line:
[(line[0])] = [line,]
it means that there is no first (line[0]) character in the line - in other words, the line is blank. So you need to ignore blank lines
updating the dictionary can be done as follows:
def updateDictionary(namesDict):
newname = input('What is your name?')
key = newname[0]
if key not in namesDict:
namesDict[key] = []
item = namesDict[key]
if newname in item:
print(newname, 'is already in the dictionary')
else:
item.append(newname)
print(newname, 'added to dictionary')
return namesDict
Problem:
Your newDictionary() cannot produce the dictionary because probably there is an empty line in your file.
Solution:
collections.defaultdict will make things easier:
from collections import defaultdict
def newDictionary():
names = defaultdict(list)
with open('file.txt','r') as f:
for line in f:
line = line.strip()
if line:
names[line[0]].append(line)
return names
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()