如何从python字典中提取相应的值?

时间:2018-09-03 12:02:37

标签: python dictionary sharp

我写了一个简单的python,它给出了系统如何运行的想法,但总数没有计算出来。现在我想要的是获取对应的值(即圆锥类型,每个勺的勺子口味和每个浇头的浇头口味)并计算总成本,最后显示详细选择的项目(项目->价格和数量)以及总和。

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)

我想简单地通过传递数字来获得所选项目。例如:“ 1”代表“普通”圆锥形。

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},
)

3 个答案:

答案 0 :(得分:1)

只需过滤元组以获取(唯一的)有效条目,并获取其价格

def get_price(cone_types, cone_name):
    return [cone['price'] for cone in cone_types if cone['name']==cone_name][0]

但是,如果您只有名称和价格,直接将字典编成

 cone_types {'plain': 2, 'wafle': 3}

,其他命令也是如此。这就是字典的使用方式,密钥应具有区分性。

答案 1 :(得分:1)

我想添加到blue_note答案中,并建议使用Enum来获取锥体类型,如下所示:

  class ConeType (enum.Enum):
        PLAIN = 1
        WAFLE = 2

print(ConeType(1).name);

答案 2 :(得分:1)

您可以将库存数据结构更改为int:-details字典,而不是当前的字典列表。

例如:

cone_type = {1:["Plain", 2], 2:["Waffle", 3]}

对于普通圆锥体,使用cone_type[1][0]访问名称,使用cone_type[1][1]访问价格。

您还可以考虑为锥体,风味和浇头分别创建一个类。然后,您可以将它们用作字典的值,而不是列表。这样做可以使您以cone_type[1].getName()cone_type[1].getPrice()的形式访问产品信息,这很容易阅读!