我在操作字典的值时遇到了问题。就我的代码而言,我似乎无法让字典显示任何内容,更不用说将菜单键分配给 specialMenu,如果任何值为 20 美元或更多。
有人可以通过显示和解释字典的语法来提供帮助,仅显示 20 美元或更多的任何值以及如何将它们分配给 specialMenu 字典?
我读入的 txt 文件的信息如下:
Ham and Egg Sandwich $15.75
Bacon and Cheese Plate $9.50
Tuna Salad $12.30
Ceasar Salad $8.00
Beef Soup $9.00
Spicy Beef Barbeque $20.00
Pork Barbeque $18.00
Oven Chicken Barbeque $15.00
Pulled Beef Barbeque Burger $25.00
House Salad $5.00
Turkey Burger $17.00
Mushroom Swiss Burger $15.00
Full Rack of Ribs $22.50
Half Rack of Ribs $11.25
Cheese Cake $9.50
House Tea $3.00
Champagne $20.00
Pellegrino $5.40
White Wine $7.50
Red Wine $11.00
这是我的代码:
menu = {}
specailMenu = {}
def getMenu():
"""Displays the menu.txt file"""
print("Here is our current menu: n")
inputFile = open("standardMenu.txt", 'r')
print("{:<30} {:<10}".format("Item", "Price"))
for line in inputFile:
itemInfo = line.split("$")
itemName = itemInfo[0].strip()
itemPrice = itemInfo[1].strip()
menu[itemName] = itemPrice
print("{:<30} ${:<10.2f}".format(itemName, float(itemPrice)))
print("n")
inputFile.close()
getSpecailMenu(menu)
return
def getSpecailMenu(menu):
"""Takes Menu items $20 or more and adds them to Specail Menu"""
#sortedByValue = {k:v for k,v in sorted(menu.items(),key = lambda v:v[1])}
for k,v in menu.items():
if v == 20:
specailMenu.append(k)
print(specailMenu)
"""viewMenu(specailMenu)
print("The total average cost of the Specail Menu is ",mean(specailMenu))"""
return
def viewMenu(specaiMenu):
"""Displays the Menu"""
print("Here is our Specail Menu")
print("{:<30} {:<10}".format("Item", "Price"))
for x, y in specailMenu.items():
print("{:<30} ${:<10.2f}".format(x, float(y)))
def mean(x):
"""find the average of the menu cost"""
total = 0
for count in x:
total += count
return total / len(x)
def ext():
"""exits the program"""
input("Hit any button to exit: ")
exit
return
def main():
"""The main function for this script"""
getMenu()
ext()
if __name__ == "__main__":
main()
当然,您可以迭代键值对,然后像这样打印您感兴趣的键值对(somedict
字典):
for key, value in somedict.items():
if value >= 20:
print(value)
如果您想要一个只包含您感兴趣的项目的新词典,您可以调整:
newdict = dict()
for key, value in somedict.items():
if value >= 20:
newdict[key] = value
您还可以使用字典理解,它以更紧凑的方式实现相同的目的:
newdict = {key: value for key, value in somedict.items() if value >= 20}
令人惊讶的是,没有人指出您的代码的实际问题:项目价格是字符串,然后您尝试将其与始终False
== 20
进行比较。如果曾经True
过,你会得到一个AttributeError
,因为字典没有.append()
方法。
修复是双重的。首先,将物料价格转换为数值:
def getMenu():
...
for line in inputFile:
...
menu[itemName] = float(itemPrice)
...
然后,修复特殊菜单功能:
# specailMenu should be spelled specialMenu
def getSpecialMenu(menu):
for k, v in menu.items():
if v >= 20: # need >= comparator
specialMenu[k] = v
...
现在,谈谈一些Python的东西:
- 函数和变量通常使用
snake_case
- 即用下划线分隔的小写单词
你 - 不应该在你的字典中使用全局变量——一般来说,你应该完全避免使用全局变量,除非你有一个很好的理由并且知道你在做什么。
- 使用
with
块打开和关闭文件 - 编写一个单独的
menu_printer()
函数,该函数将采用任何字典菜单并打印出来 - 脚本的"main"函数应该包含在
if __name__ == "__main__"
块中,不需要单独的main()
函数,事实上,稍后当您开始导入自己的模块时,您将不希望导入的对象中存在这样的函数
以下是考虑到这些更改后代码的外观:
# `with` automatically closes the file when done
def get_menu(file_path: str) -> dict:
menu = {}
with open(file_path, "r") as f:
for line in f.readlines():
item, price = line.strip().split(" $")
menu[item] = float(price)
return menu
def get_special_menu(menu: dict) -> dict:
special_menu = {}
for item, price in menu.items():
if price >= 20:
special_menu[item] = price
return special_menu
def menu_printer(menu: dict, header: str):
print(header)
for item, price in menu.items():
print("{:<30} ${:<10.2f}".format(item, price))
if __name__ == "__main__":
menu = get_menu("standardMenu.txt")
menu_printer(menu, "Main menu")
special_menu = get_special_menu(menu)
menu_printer(special_menu, "Special menu")
我读到:specailMenu = {}
然后我读到你getSpecailMenu
定义中的specailMenu.append(k)
。这应该会引发异常。字典不能在 Python 中附加:
Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> myDic = {}
>>> myDic.append("Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
>>> exit()
另外,你的意思是拼写特殊而不是特殊吗?
不是最pythonic的方式,但它会帮助你前进:
要循环访问字典的所有键并打印值,请执行以下操作:
myDic = {0: "My", 1: "cool", 2: "dictionary."}
for everyKey in myDic.keys():
print(myDic[everyKey])
这将允许您访问字典中的每个key:value
对。 要覆盖或将新的key:value
对分配到字典中,请执行以下操作:
myDic = {}
myDic[0] = "My" # Add a new key:value pair
myDic[1] = "cool" # Add a new key:value pair
myDic[0] = "dictionary." # Overwrite the value already assigned to key 0
编辑1: 请记住,键只能是不可变的对象。 https://docs.python.org/3/tutorial/datastructures.html