How to multiply each key by another key in dictionaries? - python

I'm doing course in codeacademy and i'm on lession Something of Value
In my final task i have to For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total.
My code:
for cena in prices:
total = prices[cena]*stock[cena]
print total
It's printing 0.
I also tried this:
for cena in prices:
for ilosc in stock:
total = prices[cena]*stock[ilosc]
print total
It's also returning 0.
EDIT: Whole code:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for cena in prices:
for ilosc in stock:
total = prices[cena]*stock[ilosc]
print total

It's printing 0 because the product of the "last" items in the dictionary is 0. If you want to know the products of each item in turn then you need to print inside the loop. If you want a total then you should either add to the existing value or use sum() with a generator expression (genex).

This worked for me
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for key in prices:
price_of_stock = prices[key] * stock[key]
print price_of_stock
total = total + price_of_stock
print total

What about:
from itertools import chain
results = dict()
for k, v in chain(prices.iteritems(), stock.iteritems()):
if k in results:
results[k] *= v
else results[k] = v

I am also doing this course.My ansewer as below:
total=0
sums=0
for key in price:
print key
print "price: %s" % price[key]
print "stock: %s" % stock[key]
for x in stock:
sums=stock[x]*price[x]
print sums
total+=sums
print total
Mybe can give you a ref.

Related

Addition in Dictionaries w/ Lists

DRAFT 1:
I am a beginner programmer and would really appreciate some help on a section of a project I am doing:
dict = {
'l1' : ["a1", 2],
'l2' : ["a2", 3],
'l3' : ["a3", 10]
}
I would like to sum up the numerical values to a variable
e.g.
total = 15
Thank you!
DRAFT 2:
Thank you for your comments. I will attach the code below:
#Ask user how many items are being checked out
item_amount = int(input("How many items will you be checking out?: "))
#Create a dictionary that creates multiple lists for our items for iteration
obj = {}
for i in range(1, item_amount + 1):
obj['l' + str(i)] = []
#For each item, prompt for name, quantity, unit price
for i in range(1, item_amount + 1):
print("ITEM {}\n".format(i))
item_name = input("Item Name: ")
item_quantity = int(input("Item Quantity: "))
item_unit_price = float(input("Unit Price: "))
item_subtotal = item_quantity * item_unit_price
print('\n')
obj['l' + str(i)] = [item_name, item_quantity, item_unit_price, item_subtotal]
#Computations
print("Item\tQuantity\tUnit Price ($)\tSubtotal")
for x, y in obj.items():
for i in range(1, item_amount + 1):
print(y[i][0]'\t'y[i][1]'\t'y[i][2]'\t'y[i][3])
print('\n')
#total =
#sales_tax = 0.8*total
#grand_total = total + sales_tax
In regards to my question, I am trying to work out total. Total is the sum of the subtotals
Use sum() built-in method:
dct = {
'l1' : ["a1", 2],
'l2' : ["a2", 3],
'l3' : ["a3", 10]
}
print(sum(v for (_, v) in dct.values()))
Prints:
15
For the draft one:
You can simple do:
dict = {
'l1' : ["a1", 2],
'l2' : ["a2", 3],
'l3' : ["a3", 10]
}
result =0
for x in dict:
result+=dict[x][1]
print (result)
to loop through all key values in the dictionary.
For the second draft you can do same the in showing the result in the end and convert numeric values to strings like this:
print(obj[x][0]+'\t'+str(obj[x][1])+'\t'+str(obj[x][2])+'\t'+str(obj[x][3]))
print('\n')
So the whole code will be:
obj = {}
for i in range(1, item_amount + 1):
obj['l' + str(i)] = []
#For each item, prompt for name, quantity, unit price
for i in range(1, item_amount + 1):
print("ITEM {}\n".format(i))
item_name = input("Item Name: ")
item_quantity = int(input("Item Quantity: "))
item_unit_price = float(input("Unit Price: "))
item_subtotal = item_quantity * item_unit_price
print('\n')
obj['l' + str(i)] = [item_name, item_quantity, item_unit_price, item_subtotal]
#Computations
print("Item\tQuantity\tUnit Price ($)\tSubtotal")
for x, y in obj.items():
for x in obj:
print(obj[x][0]+'\t'+str(obj[x][1])+'\t'+str(obj[x][2])+'\t'+str(obj[x][3]))
print('\n')
Hope I helped you. Have a nice time!!!

How to modify the value for a key in a dictionary?

So I'm trying to create a program that can take an order, retrieve it from stock and output the cost. When I do so I get a price of all the items chosen in stock. Any help?
import time
def compute_bill(component):
total = 0
for item in component:
total += prices[item_p]
return total
def localTime():
localtime = time.asctime(time.localtime(time.time()))
return localtime
stock = {
"I7": 2,
"Keyboard": 3,
"Mouse": 2,
"GPU": 4
}
prices = {
"I7": 250,
"Keyboard": 15,
"Mouse": 12,
"GPU": 350
}
item_p = ''
item_p = input("Please input the item you would like: ")
quantity = int(input("Please input the quantity you would like: "))
if item_p in stock:
print("X ordered a ", item_p,"at", localTime()," Which comes to a total of £", compute_bill(item_p))
else:
print("Error")
Example Output:
Please input the item you would like: Keyboard
X ordered a Keyboard at Fri Feb 9 17:16:09 2018 Which comes to a total of £ 120
I'd replace:
def compute_bill(component):
total = 0
for item in component:
total += prices[item_p]
return total
with:
def update_stock(component):
global stock
stock[component] -= quantity
def compute_bill(component):
update_stock(component)
return quantity * prices[component]
Your compute_bill function should be implemented simply like this:
def compute_bill():
return prices[item_p] * quantity

Why can't I print the result from within the function?

I'm working through the beginner's Python course in CodeAcademy. This is part of one of the exercises, where you're "checking out" at a grocery store, but I wanted to the code to print the final bill/"total" rather than just returning "total". I don't understand why it's not printing. I have tried putting it at the end, after the iteration, and, as here, within the recursion (before returning the total) to see if it'll print after each step. When I run this code, nothing displays.
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
food = shopping_list
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print total
return total
Edit:
These also aren't giving me a readout:
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #tried 0-5 indentations, same blank result
Yet
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #tried 0-5 indentations, same blank result
return total
print compute_bill(food)
Returns
Total is $ 5.5
5.5
While - I did find a solution...
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
return total
print "Total is $",compute_bill(food)
Returns
Total is $ 5.5
...but I'm confused as to why I can't just print the variable total, which should have been updated. And why it works there, but not as a feed in the function. This is just a question from an exercise, but I'm having trouble figuring out why it's doing this.
In your first example,
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
food = shopping_list
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print total
return total
You define a function def compute_bill. You never call that function. The function is executed iff it's called, e.g. compute_bill(["banana"])
I'm not sure I quite understood the problem, but you said
but I'm confused as to why I can't just print the variable total, which should have been updated.
If you try to print total from outside the function it will not work, since the total variable is only declared within the function. When you return total you allow the rest of your code to get the data from outside your function, which is why print computeBill(food) does work.
Edit, also if you want to print the total at each iteration, your code:
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total
Should definitely have this indentation, which means you'll print every time you iterate in the for loop (if you leave it as it was, it'll only print after the for).
The print statement is the part of your function compute_bill(..), it won't be executed until and unless you call the function compute_bill(..).
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #this works
compute_bill(food) # call the function it has the print statement

Can't figure out a Python exercise with dictionaries

I have the following code:
shoppingList = ["banana","orange","apple"]
inventory = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def calculateBill(food):
total = 0
for k in food:
total += prices[k]
return total
calculateBill(shoppingList)
The exercise tells me to complete the function following these instructions:
Don't add the price of an article in your bill if it is not in your inventory.
After you buy an article, substract one from the inventory.
I don't know how to do it and I don't know if I have any other mistakes in my code.
If it isn't clear, the value in inventory is the stock of that item, and the value in "prices" is the price.
First of all, I don't see comida defined anywhere before its use. I'll assume that by comida, you mean food.
Here is a simple solution:
def calculateBill(food):
total = 0
for k in food:
if inventory.get(k, 0) > 0:
total += prices[k] # updates total
inventory[k] = inventory[k] - 1 # updates inventory
return total
You could do the following
def calculateBill(food):
total = 0
for k in food:
if k in inventory:
if inventory[k] > 0:
total += prices[k]
inventory[k] = inventory[k] - 1
else:
print 'There are no %s in stock' % k
else:
print 'dont stock %s' % k
return total
For 1)
if k in inventory:
Will check if the key is present in your inventory dict.
For 2)
inventory[k] = inventory[k] - 1
Will substract 1 from your inventory
One flaw in this code is that it does not check that the inventory count is above 0 before allowing to buy. So
if inventory[k] > 0:
Does this.
Here's a complete solution.
class Error(Exception):
"""Base class for Exceptions in this module"""
pass
class QtyError(Error):
"""Errors related to the quantity of food products ordered"""
pass
def calculateBill(food):
def buy_item(food_item, qty=1, inv_dict=None, prices_dict=None):
get_price = lambda item,price_dct: price_dct.get(item,9999999)
if inv_dict is None:
inv_dict = inventory
if prices_dict is None:
prices_dict = prices
if inv_dict.get(food_item, 0) >= qty:
inv_dict[food_item] -= qty
return sum(get_price(food_item, prices_dict) for _ in range(qty))
else:
raise QtyError("Cannot purchase item '{0}' of quantity {1}, inventory only contains {2} of '{0}'".format(food_item, qty, inv_dict.get(food_item,0)))
total = sum(buy_item(food_item, 1, inventory, prices) for food_item in food)
return total

Python - simplify repeated if statements

I am very new to python and looking for a way to simplify the following:
if atotal == ainitial:
print: "The population of A has not changed"
if btotal == binitial:
print: "The population of B has not changed"
if ctotal == cinitial:
print: "The population of C has not changed"
if dtotal == dinitial:
print: "The population of D has not changed"
Obviously _total and _initial are predefined.
Thanks in advance for any help.
You can use two dictionaries:
totals = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
initials = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
for k in initials:
if initials[k] == totals[k]:
print "The population of {} has not changed".format(k)
A similar way is first determining not changed populations:
not_changed = [ k for k in initials if initials[k] == totals[k] ]
for k in not_changed:
print "The population of {} has not changed".format(k)
Or, you can have a single structure:
info = {'A' : [0, 0], 'B' : [0, 0], 'C' : [0, 0], 'D' : [0, 0]}
for k, (total, initial) in info.items():
if total == initial:
print "The population of {} has not changed".format(k)
You could organize all the pairs into a dictionary and cycle though all the elements:
populations = { 'a':[10,80], 'b':[10,56], 'c':[90,90] }
for i in populations:
if populations[i][1] == populations[i][0]:
print(i + '\'s population has not changed')
Another way (2.7) using an ordered dictionary:
from collections import OrderedDict
a = OrderedDict((var_name,eval(var_name))
for var_name in sorted(['atotal','ainitial','btotal','binitial']))
while True:
try:
init_value = a.popitem(last=False)
total_value = a.popitem(last=False)
if init_value[1] == total_value[1]:
print ("The population of {0} has "
"not changed".format(init_value[0][0].upper()))
except:
break

Categories

Resources