Updating Dictionary in a loop Python [duplicate] - python

This question already has answers here:
How can I add new keys to a dictionary?
(19 answers)
Closed 4 years ago.
I am creating records in dict data type in python. How can I add new items in the dict by using while loop as we do in tuples by using:
tuple += (rec)
When I use this code it will add elements in the tuple no matter how much. How to perform the same task with a dict
while True:
name = input('Student Name: ')
while True:
course = input('Course Name: ')
courses.append(course)
print('You have entered', len(courses), 'course(s)')
ch_course = input('Would you like to add a new course [Y]or[N]: ')
if ch_course == 'y' or ch_course == 'Y':
continue
else:
stdrec = ({name : courses})
break
ch_name = input('Would you like to add a new record [Y]or[N]: ')
if ch_name == 'n' or ch_name == 'N':
print(stdrec)
break

To add to a dict named stdrecs, you would store a new key/value pair, i.e stdrecs[name] = courses. This would look like:
stdrecs = {}
while True:
name = input('Student Name: ')
courses = []
while True:
course = input('Course Name: ')
courses.append(course)
print('You have entered', len(courses), 'course(s)')
ch_course = input('Would you like to add a new course [Y]or[N]: ')
if ch_course.upper() == 'Y':
continue
else:
stdrecs[name] = courses
break
ch_name = input('Would you like to add a new record [Y]or[N]: ')
if ch_name.upper() == 'N':
print(stdrecs)
break

Related

why i am getting blank list as output in python even after appending item in it?

#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.

Unable to get value from converted frozen set python 3

I am self-learning Python (no prior programming experience) and I am trying this question:
ask the user to input as many bank account numbers as they’d like, and store them within a list initially. once the user is done entering information, convert the list to a frozenset and print it out.
This is my code:
# create global variables
b_accounts = []
fzb_accounts = frozenset()
# Create add account function
def addAccount(account):
b_accounts.append(account)
print('Account number: {} has been added'.format(account))
return b_accounts
# create covert from a list to a frozenset function
def convertFz():
if b_accounts:
globals()['fzb_accounts'] = frozenset(b_accounts)
return fzb_accounts
else:
print('List of account does not exist!')
# create show account function
def showAccount():
convertFz()
if fzb_accounts:
#print('Here your enique entered accounts:{}'.format(fzb_accounts))
for acc in fzb_accounts:
print(acc)
else:
print('No account!')
# create main function
def main():
done = False
while not done:
ans = input('Please select add/show/quit account: ').lower()
if ans == 'add':
account = input('Enter account number: ')
addAccount(account)
elif ans =='show':
showAccount()
elif ans =='quit':
done = True
print('Bye!')
else:
print('Invalid option')
main()
I want to add the following account numbers:
1234
12345
1234
the output should be:
1234
12345
Thank all, code updated and work as expected.

Add yes/no confirmation in python 3.X [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a function that allows a user the ability to add data via input. I would like to add a confirmation step that will allow them to answer yes or no to continue. If they select no it should allow them to restart the function of adding data to the list. I also want to make sure they answer with Y, YES, y, yes, N, NO, n, no. What would be the best way to accomplish this? I've tried several solution I've found online but I end up not being able to get out of the loop of asking yes or no. Thanks in advance.
def item_list(): # Create a list
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
items = item_list()
print(items)
answer = input("Continue?")
if answer.lower() in ["y","yes"]:
# Do stuff
else if answer.lower() in ["n","no"]:
# Do other stuff
else:
# Handle "wrong" input
My answer would be extension of #B. Plüster but it allows slightly bigger range of the inputs and prevent rejections of case-sensitive typos:
answer = input("Continue?")
if answer.upper() in ["Y", "YES"]:
# Do action you need
else if answer.upper() in ["N", "NO"]:
# Do action you need
You could create a wrapper function which calls your other function. In the wrapper function, use another loop to confirm items.
# wrapper function
def item_list_wrapper():
while True:
# call your function at the start of each iteration
final_items = item_list()
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() in ('n', 'no'): # using this elif for readability
continue
else:
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
return final_items
# your original function
def item_list():
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
Then call it as you'd normally call it.
items = item_list_wrapper()
print(items)
In the item_list_wrapper function, note that the line with items = item_list() will renew the list every time. If you want the user to continue adding existing items, you could switch the order of commands around.
def item_list_wrapper():
final_items = item_list() # call the function at the start
while True:
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() not in ('n', 'no'):
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
# call your function at the start of each iteration
new_items = item_list()
# add new items to previous items
final_items += new_items
return final_items
Don't know whether this is efficient enough.
items = list()
tr = [" Y", "YES", "y", "yes"]
fs = ["N", "NO", "n", "no"]
item_int = 0
def item_list(): # Create a list
global item_int
global items
response = input("\nDo you want to enter data: ")
if response == "":
return
if response in tr:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
items.append(item)
elif response in fs:
item_int=0
print("List cleared!")
items.clear()
item_list()
item_list()
print(items)

Python Grocery List Python 3 Codio Challenge

So I am looking for a way to add separate items to a list in the form of individual dictionaries that contain the grocery item's name, price, and quantity. I only started programming a few weeks ago so please forgive my horrendous code and beginner mistakes.
grocery_item = dict()
current_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
current_item['name'] = str(input('Item name: '))
current_item['quantity'] = int(input('Amount purchased: '))
current_item['cost'] = float(input('Price per item: '))
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice == 'c':
stop = True
else:
stop = False
print(grocery_history)
When I input the information of two items (ie spam and eggs) I get the following output:
[{'name': 'Eggs', 'quantity': 12, 'cost': 1.5}, {'name': 'Eggs', 'quantity':
12, 'cost': 1.5}]
Instead of creating two different items the output just repeats the most recent one I entered. I am making some basic semantic error and I can't figure out how to populate the "grocery_history" list with different items from the user input loop. I tried using pythontutor.com for help but was just berated for being stupid. Any help is appreciated.
Try doing this:
grocery_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
current_item = dict()
current_item['name'] = str(input('Item name: '))
current_item['quantity'] = int(input('Amount purchased: '))
current_item['cost'] = float(input('Price per item: '))
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice == 'c':
stop = True
else:
stop = False
print(grocery_history)
By creating a new dictionary in each loop you'll avoid the duplicate error that you're seeing.
You should move the current_item dictionary into the while, for example:
while True:
current_item = {}
# accepts user inputs here
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice != 'c':
break
Some other notes:
No need to initiate choice = 0 before the loop.
Use break to stop the loop as soon as possible without going back to check the condition again
You're getting this because dictionaries in Python are mutable objects: this means that you can actually modify their fields without creating a brand new one.
Follow this link if you want to understand more deeply what are the main differences between mutable and immutable objects.
This is your code slightly modified, and working:
grocery_history = []
while True:
name = input('Item name: ').strip()
quantity = int(input('Amount purchased: '))
cost = float(input('Price per item: '))
current_item = {'name':name, 'quantity':quantity, 'cost':cost}
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit: '))
if choice == 'q':
break
print(grocery_history)

loop through python list index

I Have a list, and every time I enter "N" in my program I want the list to print the contents of the next index.
categories = ["Produce", "Meat", "Dairy" ,"Misc"]
...
elif item == "N":
for d in categories[:1]:
d = categories[0]
d += 1
print(d)
I understand that the above code is trying to add an integer to a string and throwing the error. What I haven't been able to figure out is how to increment the index.
I have looked at a few other posts concerning similar problems but it the solutions aren't clicking for me out of context.
Sample output of what it should look like
Add Item to list
Produce
>>Tomatoes
>>Grapes
Meat
>>Hamburger
Dairy
>>
Entire program
def add_item():
exit_list = ["F", "Finished"]
lists = []
start = input("Would you like to add an item to the list? Y/N")
print("Add Item to list")
categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]
print(categories[0])
while start in ('y', 'Y'):
item = input(">>")
if item in exit_list:
break
elif item == "N":
for d in categories[:1]:
i = 0
i +=1
d = categories[i]
print(d)
elif item:
lists.append(item)
else:
print("ok")
print(lists)
return lists
add_item()
This code will keep track of an index and increment it each time it's used:
i = 0
categories = ["hey", "1", "2" ,"3"]
...
elif item == "N":
print(categories[i])
i += 1
And note that this code will eventually go out of bounds. If you want to wrap around you can do e.g. % len(categories) on i.
Most of the time it is possible, if not better, to avoid using index in Python. One way in your case would be to use a generator on your list. The following code will quit when the user enters q, print the next item when the user enters n, and do nothing if the input is something else.
categories = ["hey", "1", "2" ,"3"]
user_input = None
# Transform your list into an iterator
categories = iter(categories)
# While the user doesn't want to quit
while user_input != "q":
# The user's input is transformed to lower case
user_input = input("What do you want to do ? ").lower()
if user_input == "n":
try:
# We print the next value on the iterator i.e. the next
# value in your list
print(next(categories))
except StopIteration:
# Raised when the iterator reached the end i.e. when we
# have printed all the values in the list
print("You've printed all the list!")
break
One possible output is:
What do you want to do ? hello # Nothing happens here
What do you want to do ? n
hey
What do you want to do ? n
1
What do you want to do ? n
2
What do you want to do ? n
3
What do you want to do ? n
You've printed all the list!
Note that this example is using Python3+
def add_item():
exit_list = ["F", "Finished"]
lists = []
start = input("Would you like to add an item to the list? Y/N")
print("Add Item to list")
categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]
print(categories[0])
i=0
while start in ('y', 'Y'):
item = input(">>")
if item in exit_list:
break
elif item == "N":
i +=1
print(categories[i])
elif item:
lists.append(item)
else:
print("ok")
print(lists)
return lists
add_item()

Categories