在只打印的情况下迭代字典

2024-09-28 03:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让它只打印一次值。好像我在字典里有钥匙的时候,它就印了很多遍

movies = {
    '2005': ["Munich", "Steven Spielberg"],
    '2006': ["The prestige", "Christopher Nolan", "The Departed", "Martin Scorsese"],
    '2007': ["Into the Wild", "Sean Penn"]
    }


choice =input("Enter a year between 2005 and 2016:\n")

for i in movies:
    print(movies[choice],'\n')

2005年我的作品将是慕尼黑,史蒂芬斯皮尔伯格三次当我只需要一次

谢谢


Tags: the字典movies钥匙martinchoicechristopherinto
2条回答

你应该

for movie in movies[choice]:
    print(movie)

您正在迭代字典的键-因为有3个键,所以您的行被打印3次

这是正常的,因为你循环看电影。如果你只想拥有一次,那么你可以做到

choice =input("Enter a year between 2005 and 2016:\n")
print(movies[choice],'\n')

相关问题 更多 >

    热门问题