How to extract corresponding value from python dictionary? - python

I wrote simple python which gives idea how the system performs but the total is not calculated. Now what I want is get the corresponding value (i.e. cone type, Scoop flavor for each scoop, and Topping flavor for each topping) and calculate total cost and finally displaying the items chosen in details (item-->price and quantity) and the total sum.
customername = input("Enter the customer's name....")
ic_no = int(input("Enter the number of ice-creams you want to buy"))
total = {}
for i in range(1, ic_no + 1):
print("For item ", i)
cone = int(input("Enter the cone type: "))
scoop = int(input("Enter the scoop amount: "))
for j in range(1, scoop+1):
#select flavor type for each scoop
flavor = int(input("Entr No."+ str(j) +" flavor"))
topping = int(input("Entr the toppings amount: "))
for k in range(1, topping+1):
#select flavor type for each topping
top_flavor = int(input("Entr No." + str(k) +" topping flavor"))
print("Total price is ", total)
I want to get the selected items simply by passing number. For eg: 1 for 'plain' cone type.
cone_type = (
{"name": "Plain", "price": 2},
{"name": "Wafle", "price": 3},
)
scoop_flavor = (
{"name": "Mint", "price": 1},
{"name": "Caramel", "price": 1},
{"name": "Chocolate", "price": 1},
{"name": "Apple", "price": 1},
)
topping_flavor = (
{"name": "Chocolate", "price": 1},
{"name": "Caramel", "price": 0.5},
{"name": "Peanut", "price": 0.5},
{"name": "Coconut Sprinkle", "price": 0.25},
)

I would like to add to blue_note answer and would suggest to use Enum to get the cone_type as below:
class ConeType (enum.Enum):
PLAIN = 1
WAFLE = 2
print(ConeType(1).name);

Just filter the tuple to get the (only) valid entry, and get its price
def get_price(cone_types, cone_name):
return [cone['price'] for cone in cone_types if cone['name']==cone_name][0]
However, if you only have name & price, it would probably be better to directly form you dictionary as
cone_types {'plain': 2, 'wafle': 3}
and similarly for other dicts. That's how dictionaries are meant to be used, the key should have discriminative value.

You could change your inventory data-structures to be a dictionaries of int:list-of-details, instead of your current lists of dictionaries.
For example:
cone_type = {1:["Plain", 2], 2:["Waffle", 3]}
For the plain cone, the name is accessed with cone_type[1][0], and the price with cone_type[1][1].
You might also consider creating a class each for cones, flavors and toppings. Then, you can use these as values for the dictionaries, in place of lists. Doing so would allow you to access product information as cone_type[1].getName() and cone_type[1].getPrice(), which is a lot easier to read!

Related

Calculating sum of ordered list of dictionaries

I am trying to find out how to return a sum of several values given in a order list of dictionaries
menu = {
1: {"name": 'espresso',
"price": 1.99},
2: {"name": 'coffee',
"price": 2.50},
3: {"name": 'cake',
"price": 2.79},
4: {"name": 'soup',
"price": 4.50},
5: {"name": 'sandwich',
"price": 4.99}
}
def calculate_subtotal(order):
return subtotal
def take_order():
display_menu()
order = []
count = 1
for i in range(3):
item = input('Select menu item number ' + str(count) + ' (from 1 to 5): ')
count += 1
order.append(menu[int(item)])
return order
def calculate_subtotal(order) should accept one argument which is the order list and return the sum
of the prices of the items in the order list.
Do I have to use a for loop to iterate through the values and sum each value?
How do I access the dictionaries inside the list?
Let's say a person orders the following:
orders = [
{"name": "espresso", "price": 1.99},
{"name": "espresso", "price": 1.99},
{"name": "soup", "price": 4.99},
]
You now have a list of dict. Indexing into the list returns a reference to a dictionary. For example:
first_order = orders[0]
print(first_order)
Would print:
{'name': 'espresso', 'price': 1.99}
Using that knowledge, you can loop through the orders like so:
total = 0.0
for order in orders:
total += order["price"]
Each order will be a dict like you saw above.
You can also use a comprehension if you're comfortable with them.
total = sum(order["price"] for order in orders)

How can I get "price"s value in this dict list?

products = [
{"name": "samsung s6", "price": 3000},
{"name": "samsung s7", "price": 4000},
{"name": "samsung s8", "price": 5000},
{"name": "samsung s9", "price": 6000},
{"name": "samsung s10", "price": 7000}
]
for product in products:
for a, b in product.items():
print(b)
hey guys. i want to get price key's value and calculate total price all of items i have. what's the best way to get it?
To get the value of each dict's price key, simply access it using the my_dict["key"] syntax. Here is a basic way to sum the prices using a for loop:
total = 0
for product in products:
total += product["price"]
print(total)
The slightly more advanced method is to create a sequence of prices using a list comprehension or generator expression, and pass it to the built-in sum function, like this:
total = sum(product["price"] for product in products)
The short version:
print( sum( x['price'] for x in products ) )
This is the same as:
newList = []
for x in products:
newList.append( x['price'] )
out = sum( newList )
print( out )

Python: How to filter dictionary?

I want to achieve the following, but using dictionary.
name_selected = "Jason"
if name_selected == "John":
age = 10
gender = "Male"
elif name_selected == "Jason":
age = 20
gender = "Male"
print(age, gender)
data = {"name": ["John", "Jason"],
"age": [10, 20],
"gender": ["Male", "Male"]}
That's a poor data organization. It would be better if you made the names the dictionary keys:
data = {
"John": { "age": 10, "gender": "Male"},
"Jason": { "age": 20, "gender": "Male"}
}
age = data[name_selected]["age"]
gender = data[name_selected]["gender"]
But if you're stuck with your data structure, you can use index() to get the index in the name element, then use that to get the corresponding values in the other elements.
try:
index = data['name'].index(name_selected)
age = data['age'][index]
gender = data['gender'][index]
except:
print(f'{name_selected} not found')
Since you're testing name_selected == ..., the possible values of name_selected are the dictionaries you want. Dictionaries are the structure that replaces if-elif lookup on a variable.
Given that, you can store the remaining data in any number of ways. Here's a tuple that you can unpack:
data = {'John': (10, 'Male'),
'Jason': (20, 'Male')}
Then you can do
age, gender = data[name_selected]
You can extend the idea with another nested dictionary:
data = {'John': {
'age': 10, 'gender': 'Male'},
'Jason': {
'age': 20, 'gender': 'Male'}
}
Now it might be better not to unpack:
person = data[name_selected]
# use person ['age'] and person['gender']
A more application-specific solution would be to make the values custom objects (like a collections.namedtuple) that would let you access the data for an individual as attributes.

Testing nested dictionaries for a user input and retrieving directly related information

I’m new to Python 3 and have been experimenting with Dictionaries but I’m having problems testing for a specific key and retrieving its related values from nested dictionaries.
I want a user defined input to be checked against nested dictionaries and if the user input is found I then want to collect the details for that item and add it to another dictionary.
E.g.
basketDict = {}
shopDict = {"Fruit": {"Apple": "2", "Banana": "3"},
"Vegetables": {"Lettuce": "5", "Potato": "7"}}
userQuery = input("What food do you want to check for? ")
userQuery = "Apple"
Desired result:
basketDict = {"Fruit": {"Apple": "2"}}
I've attempted to use dictionary comprehension to form a new dictionary of only food items (Apple, Banana, Lettuce etc.) but keep running into issues when trying to collect the related category ("Fruit"/"Vegetable" and quantity information from the nested dictionaries.
Here's my (broken) code:
basketDict = {}
shopDict = {"Fruit": {"Apple": "2", "Banana": "3"},
"Vegetables": {"Lettuce": "5", "Potato": "7"}}
shopCheck = []
userQuery = input("What food do you want to check for? ")
for category, food in shopDict.items():
for each in food:
shopCheck.append(each)
if userQuery not in shopCheck:
print("That's not available.")
else:
print(userQuery + " added to basket. ")
basketDict[category] = [food]
print(basketDict)
This code is enough for your requirements:
for category, food in shopDict.items():
if userQuery in food:
basketDict[category] = {userQuery: food[userQuery]}
But if you want to add new items to the basket, you should update it properly:
for category, food in shopDict.items():
if userQuery in food:
basketDict.update(
{category: {**basketDict.get(category, {}),
**{userQuery: food[userQuery]}}}
)
You want to merge the actual dictionary of the category (the basket's actual content) with the selected item's key-value.
Generally in python3 if you have 2 dictionaries this is the way to merge them into one:
d1 = {"one": 1, "two": 2}
d2 = {"three": 3}
merged = {**d1, **d2} # {'one': 1, 'two': 2, 'three': 3}
Because ** is used to unpack the dictionary.
Good way to understand it is if you have a function definition with some arguments, then you can call the function with a dictionary that has the argument names as keys. But you have to unpack it, otherwise you would pass the dictionary as the parameter, and not its values.
d = {"one": 1, "two": 2}
def example(one, two):
pass
example(d) would throw a TypeError, because it's missing the second positional argument, but example(**d) would work fine
Probably there's a simpler way to do this, but I just fixed your code.
When I run your code, everything inside shopDict was going to basketDict. This is because you wasn't cleaning your shopCheck variable at each for iteration.
And there was a second mistake when adding the elements to basketDict. You need to add only the food element that match the userQuery. Here's the full fixed code:
basketDict = {}
shopDict = {"Fruit": {"Apple": "2", "Banana": "3"},
"Vegetables": {"Lettuce": "5", "Potato": "7"}}
userQuery = input("What food do you want to check for? ")
for category, food in shopDict.items():
shopCheck = []
for each in food:
shopCheck.append(each)
if userQuery not in shopCheck:
print("That's not available.")
else:
print(userQuery + " added to basket. ")
basketDict[category] = {userQuery:food[userQuery]}
print(basketDict)
I'd start by creating a dictionary containing all the items you can buy, whether they're fruit or vegetables. Then I'd simply check if the required item is on that dictionary:
basketDict = {}
shopDict = {"Fruit": {"Apple": "2", "Banana": "3"},
"Vegetables": {"Lettuce": "5", "Potato": "7"}}
allVals = {}
for k, subDict in shopDict.items():
for k1, val in subDict.items():
allVals[k1] = val
userQuery = input("What food do you want to check for? ")
if userQuery not in allVals.keys():
print("That's not available.")
else:
print(userQuery + " added to basket. ")
basketDict[userQuery] = allVals[userQuery]
print(basketDict)

How can I store data in a dictionary without overriding it?

How can I store data in a dictionary in Python without overriding the existing one?
For example:
output = {}
name = raw_input("Enter name")
age = input("Enter your age")
course = raw_input("Enter course")
school = raw_input("Enter school")
output['name'] = name
output['age'] = age
output['course'] = course
output['school'] = school
The output is this.
{
"name": "Student 1",
"age": 25,
"course": "BSCS",
"school": "School 1"
}
Then, if I add another field, it overrides the existing data.
How can I store it just like this:
{
"students": [
{
"name": "Student1",
"age": 25,
"course": "BSIT",
"school": "School 1"
},
{
"name": "Student2",
"age": 26,
"course": "BSCS",
"school": "School 2"
},
{
"name": "Student3",
"age": 27,
"course": "BSCE",
"school": "School 3"
}
]
}
A key is unique, so if you want to store multiple values in one key, make the value a list or another dict, tuple, custom Object etc..
E.g.
my_dict = {}
my_dict["students"] = []
my_dict["students"].append( new_dict )
I would consider making a class or using a tuple to store the students data inside the list, however, if you want the JSON like format, you may use other dictionaries like:
new_dict = {"name": "Max", "age":12}
my_dict["students"].append( new_dict )
In case of an object you'd make something like:
class Student(object):
__init__(self, name, age):
self.name = name
self.age = age
So now you could do something like:
my_dict.append( Student("max", 12) )
You can also solve it using the inbuilt collections module and a class called defaultdict in it.
import collections as cl
output = cl.defaultdict(list)
for i in range(n):
name, age, course, school = map(str, raw_input().split())
age, key, value = int(age), "student" + str(i + 1), dict()
value["name"], value["age"], value["course"], value["school"] = name, age, course, school
output[key] = value
As far as the documentation says
This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.
Python Documentation

Categories

Resources