Hello I am trying to create the table below by using list. The product s and the prices are already in lists (priceList and productList). i have successfully created new more list where the person types in the product code and quantity (quan_inputed).
Any help would be greatly appreciated as I don't know what to do. I have tried several methods already and this is the closest I've come to getting multiple inputs at once.
Thank you
Try This:
def add_item():
code_inputed = []
quan_inputed = []
while True:
i = input("enter code: ")
if i != "END":
q = input("enter quantity: ")
code_inputed.append(int(i))
quan_inputed.append(int(q))
else:
break
return code_inputed,quan_inputed
def showRecord(code_inputed, quan_inputed):
product_info = {}
for kk in range(len(code_inputed)):
quan = quan_inputed[kk]
kk = code_inputed[kk]
price = priceList[kk]
product = productList[kk]
if kk not in product_info:
product_info[kk] = [kk, quan, price, product]
else:
product_info[kk][1] += quan
product_info[kk][2] = product_info[kk][1] * price
for x in ["Code", "Quanity", "Price", "Product"]:
print(x, end=" ")
print()
for x in product_info:
for info in product_info[x]:
print(info, end=" ")
print()
code_inputed, quan_inputed = add_item()
showRecord(code_inputed, quan_inputed)
Just to explain my comment about the other approach, I recommend storing the data in other way than just in multiple lists. For example like this:
items = [
{'code': 2, 'price': 39.95, 'quantity': 11, 'product': "Tea Set\t\t"},
{'code': 34, 'price': 19.95, 'quantity': 3, 'product': "Citrus Cather"}
]
print("Code\tProduct\t\t\tPrice $\tQuantinty\tCost $")
print("------------------------------------------------------")
for item in items:
print(f"{item.get('code')}\t\t{item.get('product')}\t{item.get('price')}\t{item.get('quantity')}\t\t\t{item.get('price') * item.get('quantity')}")
Those tabs (\t) in product name in dictionary are just to make the table nice, you should come up with nicer way to print it...
Result:
Related
product_dict = {"Jeans": 150, "Jacket": 300, "Perfume": 50, "Wallet": 125, "Glasses": 100}
#product dictonary with prices
order_history = {'Andrew':[{'Jeans':2, 'Wallet': 4}, {'Perfume':2}], 'Max':[{'Jacket': 3}]}
c_name = input('customer name: ')
print('The following is order history of, c_name')
key = order_history['c_name']
for i in range(len(key)):
print('purchase', i+1, key[i])
I am creating a retail check out program, I have a predefined products stored in a dictionary along with prices that I use in other part of program, I wanted to print the output in a more presentable like this:
This is the order history of Andrew.
Jeans Wallet Perfume Jacket
Purchase 1: 2 4
Purchase 2: 2
This is more of a console display issue rather than a python issue.
You could potentially use a library for this, such as Textualize/rich. I don't want to give you the full answer, just lead you in the right direction as it appears you are learning:
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Jeans", style="dim", width=12)
table.add_column("Jacket")
table.add_column("Perfume", justify="right")
table.add_column("Wallet", justify="right")
#add more columns as necessary
#iterate over your order history to add rows
table.add_row(
)
console.print(table)
In my opinion, creating a table in the console would look best.
Use a nested loop to print the quantity of each item, by looping over the keys of product_dict. Use end='' to print all the quantities on the same line, and use fixed-width fields in the formatting string to make everything line up.
product_dict = {"Jeans": 150, "Jacket": 300, "Perfume": 50, "Wallet": 125, "Glasses": 100}
#product dictonary with prices
order_history = {'Andrew':[{'Jeans':2, 'Wallet': 4}, {'Perfume':2}], 'Max':[{'Jacket': 3}]}
c_name = 'Andrew'
print(f'The following is order history of {c_name}')
print(' ' * 12, end='')
for product in product_dict:
print(f'{product:10}', end='')
print()
key = order_history[c_name]
for i, items in enumerate(key, 1):
print(f'Purchase {i}: ', end='')
for product in product_dict:
if product in items:
print(f'{items[product]:<10}', end='')
else:
print(' ' * 10, end='')
print()
If you want to accommodate additions to your dictionary with arbitrary length product names:
product_dict = {"Jeans": 150, "Jacket": 300, "Perfume": 50, "Wallet": 125, "Glasses": 100}
skus = list(product_dict)
width = 0
for sku in skus:
l = len(sku)
if l > width:
width = l
width = width + 2
pl = len('Purchase XX')
h = ' '.center(pl + 1,' ')
for sku in skus:
h = h + sku.center(width,' ')
#product dictonary with prices
order_history = {'Andrew':[{'Jeans':2, 'Wallet': 4}, {'Perfume':2}], 'Max':[{'Jacket': 3}]}
c_name = input('customer name: ')
print('The following is order history of', c_name)
print(h)
key = order_history[c_name]
for i in range(len(key)):
s = ''
for sku in skus:
if sku in list(key[i]):
s = s + str(key[i][sku]).center(width,' ')
else:
s = s + ' '.center(width,' ')
print('Purchase ' + str(i + 1).rjust(2,' ') + ' ' + s)
You'll get something like this:
The following is order history of Andrew
Jeans Jacket Perfume Wallet Glasses
Purchase 1 2 4
Purchase 2 2
Im currently writing an menu where you can create, read, update, delete products from a deposit, so my proffesor told me to use .txt file as a "database" not really a database but only to store some information. My question is that i searched everywhere how to create a nested list from user input and insert it in the text file and all i have right now is that i can create a list for each product like : ['Product1', 'quantity', 'price'] ['Product2', 'quantity', 'price'], but i cant create a nested list like this: [['Product1', 'quantity', 'price'], ['Product2', 'quantity', 'price']] so i can print a product with all his details like qty and price.. here is my code:
def adaugaProdus():
nume = input("Introduceti numele produsului:")
cantitate = int(input("Introduceti cantitatea :"))
pret = int(input("Introduceti pretul:"))
produse = []
produse.append(nume)
produse.append(cantitate)
produse.append(pret)
depozit = open("depozit.txt", "a")
depozit.write(str(produse))
depozit.write("\n")
depozit.close()
I've added a little bit to your code to show you that you can "nest" the lists. I think you were definitely on the right track with your answer:
#!/usr/bin/env python3
def adaugaProdus():
products = [] # Initialize the list of prducts
for product in range(2): # We'll ask user for 2 products - you can choose a different way to terminate the loop as needed
nume = input("Introduceti numele produsului:")
cantitate = int(input("Introduceti cantitatea :"))
pret = int(input("Introduceti pretul:"))
produse = []
produse.append(nume)
produse.append(cantitate)
produse.append(pret)
products.append(produse) # Adding to the list of lists
depozit = open("depozit.txt", "a")
depozit.write(str(products))
depozit.write("\n")
depozit.close()
adaugaProdus()
And here's another version using PyYAML. YAML is a format that allows the program to write the data, but more importantly it allows the program to read the program easily, too. As an important added bonus, it's easy for us dumb humans to edit!
Here's the modified program:
#!/usr/bin/env python3
import yaml # you'll need to 'pip install PyYaml' first
def adaugaProdus():
products = [] # Initialize the list of prducts
for product in range(2): # We'll ask user for 2 products - you can choose a different way to terminate the loop as needed
nume = input("Introduceti numele produsului:")
cantitate = int(input("Introduceti cantitatea :"))
pret = int(input("Introduceti pretul:"))
produse = []
produse.append(nume)
produse.append(cantitate)
produse.append(pret)
products.append(produse) # Adding to the list of lists
with open("depozit.yaml", "w") as f:
yaml.dump( products, f )
adaugaProdus()
And here's the user session and depozit.yaml file:
Introduceti numele produsului:P1
Introduceti cantitatea :1
Introduceti pretul:1
Introduceti numele produsului:P2
Introduceti cantitatea :2
Introduceti pretul:2
$ cat depozit.yaml
- - P1
- 1
- 1
- - P2
- 2
- 2
And here's an example of a program that can read depozit.yaml:
import yaml
with open("depozit.yaml") as f:
products = yaml.safe_load( f )
print(products)
And the output:
[['P1', 1, 1], ['P2', 2, 2]]
you should use dictionary :
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
# creating a list
list = ['Product1', 'quantity', 'price']
# Adding this list as sublist in myDict
myDict["key1"].append(list)
print(myDict)
I would change this to a list of dict items and then use the json standard module. It will make your life a lot easier. See the example below...
import json
def to_dict(nume, cantitate, pret):
return {
"nume": nume,
"cantitate": cantitate,
"pret": pret
}
def get_input():
nume = input("Introduceti numele produsului:")
cantitate = int(input("Introduceti cantitatea :"))
pret = int(input("Introduceti pretul:"))
return nume, cantitate, pret
produse_list = []
# one way
nume, cantitate, pret = get_input()
produse_list.append(to_dict(nume, cantitate, pret))
# other way
produse_list.append(to_dict(*get_input()))
print(produse_list)
with open("output.json", "w") as outfile:
json.dump(produse_list, outfile)
with open("output.json") as infile:
produse_list_2 = json.load(infile)
print(produse_list_2)
You can combine all inputs in a list and then append it to produse. This will create a nested list like [['Product1', 'quantity', 'price'], ['Product2', 'quantity', 'price']]:
def adaugaProdus():
nume = input("Introduceti numele produsului:")
cantitate = int(input("Introduceti cantitatea :"))
pret = int(input("Introduceti pretul:"))
produse = []
produse.append([nume, cantitate, pret]) # This is the modified line.
depozit = open("depozit.txt", "a")
depozit.write(str(produse))
depozit.write("\n")
depozit.close()
This is my code:
a = int(input())
for i in range(a):
b = input()
b = b.split(".")#creating a list
#print(b)
b[1]= b[1].lower()
b[1]=b[1].capitalize()
a=b[1]
#print(b[1])
#print(b[0] , b [1] , b[2])
dic = {}
dic_final={}
dic={b[1] : {'name':b[0] ,'lan':b[2] }}
dic_final.update(dic)
del(dic)
print(dic_final)
My input :
2
f.sara.python
m.john.java
Output has to be like :
{ 'sara':{'gender':'f' , 'lan':'python'} , 'john':{'gender':'m' , 'lan':'python'}}
But i always get the last dictionary item i wrote in the input :
{'john':{'gender':'m' , 'lan':'python'}
How can i solve it and get a dictionary like below?
{ 'sara':{'gender':'f' , 'lan':'python'} , 'john':{'gender':'m' , 'lan':'python'}}
this is a very clear solution that i came up with
num_sample = int(input("how many test cases?: "))
final = {}
for case in range(num_sample):
new_case = input("insert new case: ")
gender, name, lan = new_case.split(".")
info = {"gender": gender, "lan": lan}
final[name] = info
#access final from here
Create a global dictionary instead of creating a local one in the for loop. Moreover in your code, you are naming gender as name
a = int(input())
dic_final = {}
for i in range(a):
b = input()
b = b.split(".")
b[1]= b[1].lower()
b[1]=b[1].capitalize()
a=b[1]
dic={b[1] : {'gender':b[0] ,'lan':b[2] }}
dic_final.update(dic)
del(dic)
print(dic_final)
Output:
2
f.sara.python
m.john.java
{'Sara': {'gender': 'f', 'lan': 'python'}, 'John': {'gender': 'm', 'lan': 'java'}}
The reason you are getting only the last entry is because , you are re-initialising the dictionary for every iteration.
All you have to do is , make "dic_final" global .
You're overwriting the dic_final dictionary in the for loop each time.
This line is causing the issue dic_final={}
Solution:
Add this line before your 'for loop' and remove the declaration inside.
dic_final = dict()
Better coding style:
a = int(input())
dic_final = dict()
for i in range(a):
b = input()
gender, name, lan = b.split(".")
name = name.capitalize()
dic_final.update({name : {"gender": gender, "lan": lan}})
print(dic_final)
Output:
2
f.sara.python
m.john.java
{'Sara': {'gender': 'f', 'lan': 'python'}, 'John': {'gender': 'm', 'lan': 'java'}}
I am trying to write a basic store-front script that loops until the customer says no to the question. Each time there's input of an Item Number, I'm trying to store it and then eventually be able to match those numbers up with the Item Name and the Price (not quite yet, though)...
I am just, now, trying to get it to add to the empty list "item_nums" instead of adding the last entry and over-writing the previous numbers.
STOREKEEPER
products = ['Notebook', 'Atari', 'TrapperKeeper', 'Jeans', 'Insects',
'Harbormaster', 'Lobotomy', 'PunkRock', 'HorseFeathers', 'Pants',
'Plants', 'Salami']
prices = ['$4.99', '$99.99', '$89.99', '$3.99', '$2.99', '$299.99',
'$19.99', '$3.99', '$4.99', '$2.99', '$119.99', '$1.99']
SKUs = [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12]
item_nums = ()
quantity = []
response = ''
#MORE VARIABLES AND FUNCTIONS WILL GO HERE
print("Jay's House of Rip-Offs\n\n")
titles = ['Item Number', 'Item Name', 'Price']
data = [titles] + list(zip(SKUs, products, prices))
for i, d in enumerate(data):
line = '|'.join(str(x).ljust(16) for x in d)
print(line)
if i == 0:
print('-' * len(line))
response = str(input("Order products [Y / N]?: "))
while response != 'N':
item_nums = input("Enter an item number: ")
SKUs.append(item_nums)
response = str(input("Order products [Y / N]?: "))
if response == 'N':
break
print("Here is the list of items you ordered: ",item_nums[0])
I'm not sure why you're appending to SKU, you need a new list to track order numbers.
orders = []
while str(input("Order products [Y / N]?: ")) != 'N':
item_nums = input("Enter an item number: ")
orders.append(item_nums)
print("Here is the list of items you ordered: ", orders)
I have a dictionary in the following format:
{'Dickens,Charles': [['Hard Times', '7', '27.00']],
'Shakespeare,William': [['Rome And Juliet', '5', '5.99'],
['Macbeth', '3', '7.99']]}
I want to append to this dictionary by asking the user for the author's last and first name, which is the key, then book name, quantity, then price. If the author already exists, it should create another list of lists.
def displayInventory(theInventory):
for names, books in sorted(theInventory.items()):
for title, qty, price in sorted(books):
print("Author: {0}".format("".join(names)))
print("Title: {0}".format(title))
print("Qty: {0}".format(qty))
print("Price: {0}".format(price))
print()
def addBook(theInventory):
my_list = []
hello = True
flag = True
first = input("Enter the first name of the author: ")
last = input("Enter the last name of the author: ")
last = last[0].upper() + last[1:].lower()
first = first[0].upper() + first[1:].lower()
author = last + "," + first
book = input("Enter the title of the book: ")
book = book.lower()
book = book.title()
j = 0
if author not in theInventory:
while flag:
try:
qty = int(input("Enter the qty: "))
price = input("Enter the price: ")
my_list.append(str(book))
my_list.append(str(qty))
my_list.append(str(price))
theInventory[author] = my_list
flag = False
except ValueError:
("no")
else:
for i in theInventory[author][j]:
if theInventory[author][j][0] == book:
print("The title is already in the Inventory")
hello = False
while flag:
qty = int(input("Enter the qty: "))
if qty > 0:
flag = False
tree = True
while tree:
price = input("Enter the price: ")
my_list.append(str(book))
my_list.append(str(qty))
my_list.append(str(price))
theInventory[author].append(my_list)
j+=1
tree = False
This keeps throwing errors when I try to print theInventory from main after updating it.
File "practice.py", line 270, in <module>
main()
File "practice.py", line 254, in main
displayInventory(theInventory)
File "practice.py", line 60, in displayInventory
for title, qty, price in sorted(books):
ValueError: need more than 1 value to unpack
It doesn't update the dictionary at all if its an author that did exist previously, and after adding a new author with the values it throws the error.
The last three lines of the traceback is very helpful:
File "practice.py", line 60, in displayInventory
for title, qty, price in sorted(books):
ValueError: need more than 1 value to unpack
The error message indicates that books does not contain what you think it does (a list of lists). The traceback shows the error occurring here:
for title, qty, price in sorted(books): # <= ValueError: need more than 1 value to unpack
print("Author: {0}".format("".join(names)))
... # the rest of the loop
Wrap this loop in a try/except to see what books really contains.
try:
for title, qty, price in sorted(books):
print("Author: {0}".format("".join(names)))
... # the rest of the loop
except ValueError:
print(books)
raise
Edit:
The root cause of the error is here:
theInventory[author] = my_list
Since theInventory is supposed to contain a list of lists, change the assignment to
theInventory[author] = [my_list]