favorite_foods = {'bill': 'cake', 'alex': 'patacones'}
for name in favorite_foods:
print(f"I dont agree with your favorite food {name.title()}.")
for food in (favorite_foods.values()):
print(f"{food.title()} is delicious, but not that good!")
if food in (favorite_foods.values() endswith(s)
print(f"{food.title()} are delicous, but not that good!")
如何正确地遍历这个字典?
我想让它写
我不同意你最喜欢的食物Bill。蛋糕很好吃,但没那么好吃!我不同意你最喜欢的食物,Alex。帕塔康内干酪很好吃,但没那么好吃!我感谢所有的帮助。谢谢你。代码循环遍历所有值,而不是在一个值之后停止。我用谷歌搜索了endswith函数,看看我是否可以让代码打印不同的东西,如果值以's'结尾,但它不起作用。在我添加该行之前,它打印了以下内容:
我不同意你最喜欢的食物Bill。蛋糕很好吃,但没那么好吃!蛋糕很好吃,但没那么好吃!帕塔康内斯很好吃,但不是那么好吃!帕塔康内干酪很好吃,但没那么好吃!亚历克斯,我不同意你最喜欢的食物。蛋糕很好吃,但没那么好吃!蛋糕很好吃,但没那么好吃!帕塔康内斯很好吃,但不是那么好吃!帕塔康内干酪很好吃,但没那么好吃!我想找到一种方法来触发"are"当值为复数且"is"如果值是单数。
你可以用两件事使这个正确和简单。
使用for key, val in <dict_name>.items()
同时遍历键、值对。
在需要根据布尔值选择值时使用三元运算符。例如,print(("yum!" if tasteGood else "gross!"))
将打印&;yum!&;当味道好是真的,但印刷"恶心"!
所以把所有的东西放在一起
favFoods = {
'bill':'cake','alex':'patacones'
}
for name, food in favFoods.items():
print(f"I dont agree with your favorite food {name.title()}.")
print(f"{food.title()} {('are' if food.endswith('s') else 'is')} delicious, but not that good!")
您有大量的语法错误,而且您的if
语句正试图成为for
循环。如此:
favorite_foods = {'bill': 'cake', 'alex': 'patacones'}
for name in favorite_foods:
print(f"I dont agree with your favorite food {name.title()}.")
for food in (favorite_foods.values()):
if food.endswith('s'):
print(f"{food.title()} are delicous, but not that good!")
else:
print(f"{food.title()} is delicious, but not that good!")
使用.items()
来循环dict
。此外,如果您希望输出是一个长字符串(即,没有新行),您可以使用list
和join
。
favorite_foods = {'bill': 'cake', 'alex': 'patacones'}
output = []
for k,v in favorite_foods.items():
output.append(f"I dont agree with your favorite food {k.title()}.")
if v[-1] == 's':
output.append(f"{v.title()} are delicious, but not that good!")
else:
output.append(f"{v.title()} is delicious, but not that good!")
print(" ".join(output))
输出:
I dont agree with your favorite food Bill. Cake is delicious, but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good!