字典中的键由具有不同整数的不同元组组成,我需要用该整数打印字典中的所有值。
我试图使用dictionary.get()和dictionary.values()获取值 结合不同的for循环。
#Vegetarian = 1
#Vegan = 2
#Gluten-free = 3
a = tuple([0])
# "Joe's Gourmet Burger"
b = tuple([1,3])
# "Main Street Pizza Company"
c = tuple([1,2,3])
# "Corner Cafe"
d = tuple([1])
# "Mama's Fine Italian"
e = tuple([1,2,3])
# "The Chef's Kitchen"
rest = {a:"Joe's Gourmet Burger",
b:"Main Street Pizza Company",
c:"Corner Cafe",
d:"Mama's Fine Italian",
e:"The Chef's Kitchen"}
food = set()
veg = input("does anyone need vegetarian? yes/no ")
if veg == "yes":
food.add(1)
vegan = input("does anyone need vegan? yes/no ")
if vegan == "yes":
food.add(2)
glut =input("does anyone need gluten free? yes/no ")
if glut == "yes":
food.add(3)
for num in food:
print(num)
print(rest[num])
这将为您提供所选过敏的价值。 我希望字典能够识别元组中的键,然后打印出相应的餐厅。此外,如果用户选择了多个过敏症,则脚本应仅返回满足所有用户过敏症的餐馆。
我得到的是“ dict对象在0x000001ACC9DA4A68处的内置方法获取”
答案 0 :(得分:0)
如果用户对任何问题的回答为“是”,您是否要打印出这些值?
如果是这样的话,这将无法完全解决您的问题,但这应该为您指明正确的方向:
for num in food:
for k in rest.keys():
if num in k:
print(rest[k])
如果我的理解正确,则需要检查字典的每个键(即每个元组)中是否存在给定的数字。
@Michael Butscher的观点,这将不会很有用,因为您将拥有重复的键。相反,您可以将数据结构重组为包含每个键的餐厅列表的内容:
requirements = {
0: "None",
1: "Vegetarian",
2: "Vegan",
3: "Gluten-free"
}
requirement_restaurant_map = {
0: ["Joe's Gourmet Burger"],
1: ["Main Street Pizza Company", "Corner Cafe", "Mama's Fine Italian", "The Chef's Kitchen"],
2: ["Corner Cafe", "The Chef's Kitchen"],
3: ["Main Street Pizza Company", "Corner Cafe", "The Chef's Kitchen"]
}
food = set()
veg = input("does anyone need vegetarian? yes/no ")
if veg == "yes":
food.add(1)
vegan = input("does anyone need vegan? yes/no ")
if vegan == "yes":
food.add(2)
glut = input("does anyone need gluten free? yes/no ")
if glut == "yes":
food.add(3)
intersection = []
for num in food:
for k in requirements:
if num == k:
if not intersection:
intersection.extend(requirement_restaurant_map[k])
else:
intersection = list(set(intersection).intersection(set(requirement_restaurant_map[k])))
print(f"The following restaurants satisfy your requirements...\n {intersection}")