pandas 如何从用户输入中提取字典值

db2dz4w8  于 2023-03-16  发布在  其他
关注(0)|答案(2)|浏览(141)

我有一个字典,我用Pandas Dataframe :

`myDict = {
  "Wakanda Burger": 4.99,
  "Tony Fries": 2.99,
  "Hulk Shake": 4.55
}

df = pd.DataFrame([myDict])
print(df)`

我试图从键中提取价格,并根据用户选择的项目将其添加到小计中。

def user_order():
  subTotal = 0
  order = input("Hi, Welcome to Marvel Eateries. What would you like?: ")
  while order not in myDict.keys():
    order = input('Item not found. Try again: ')
  
  while order in myDict.keys():
    anyElse = input(f"Perfect, {order} has been added to your order. Anything else?: ")
    subTotal = subTotal + order.myDict.values()
  
  `
    if anyElse.startswith('n').endswith('o'):
      print(f"Splendid, your total is {subTotal}.")
      break
  
    while anyElse.starswith('y').endswith("s"):
      anyElse = input('What would you like?: ')
      
  return subTotal

错误:
AttributeError: 'str' object has no attribute 'myDict'
我知道有一个类似的帖子。它没有回答我的问题与用户输入。谢谢。

wwodge7n

wwodge7n1#

您的代码存在以下问题:

subTotal = subTotal + order.myDict.values()

要从myDict获取值,必须执行以下操作:

subTotal = subTotal + myDict[order]

你可以阅读更多关于python字典here的内容。

jgovgodb

jgovgodb2#

你可以尝试改变你用来访问字典的方式,下面有一个例子,你可以检查它是否适合你,如果不适合你,你可以发布你得到的错误和其余的代码。
您也可以查看此网页(https://www.w3schools.com/python/python_dictionaries_access.asp)和此网页(https://www.codecademy.com/learn/dacp-python-fundamentals/modules/dscp-python-dictionaries/cheatsheet)了解更多信息。

myDict = {
  "Wakanda Burger": 4.99,
  "Tony Fries": 2.99,
  "Hulk Shake": 4.55
}

df = pd.DataFrame([myDict])
print(df)

def user_order():
  subTotal = 0
  order = input("Hi, Welcome to Marvel Eateries. What would you like?: ")
  while order not in myDict.keys():
    order = input('Item not found. Try again: ')
  
  while order in myDict.keys():
    anyElse = input(f"Perfect, {order} has been added to your order. Anything else?: ")
    subTotal = subTotal + myDict[order] # changed this line
  
    if anyElse.startswith('n') or anyElse.endswith('o'): # changed this line
      print(f'Splendid, your total is {subTotal}.') # added f-string
      break
  
    while anyElse.startswith('y') or anyElse.endswith("s"): # changed this line
      order = input('What would you like?: ') # changed this line
      
  return subTotal

相关问题