【发布时间】:2018-02-20 17:04:06
【问题描述】:
我有一个关于字典和 for 循环的问题。在这段代码中有一个字典,我想分别打印该字典中的键和值。从 Python 的官方文档中,我发现可以使用 items() 方法,这对我来说很清楚。我不明白为什么“打印价格[x]”只会输出值,而不是键:值或键。我正在 Codeacademy 网站上运行此代码。
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
for x in prices:
print x # will print only keys
print prices[x] # will print values
谢谢。
【问题讨论】:
-
I can't understand why "print prices[x]" will give an output of only values因为它是这样工作的 -
你在你的例子中明白 x 遍历键吗?如果 price[x] 只返回键,那么它只会返回输入。