【问题标题】:Python: For loop with dictionaries (codeacademy example)Python:带有字典的 For 循环(codeacademy 示例)
【发布时间】: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] 只返回键,那么它只会返回输入。

标签: python for-loop


【解决方案1】:

您的代码正在遍历 dict 中的键。

所以,首先,您打印密钥。然后,您在 dict 中查找该键的值和 prices[x]

【讨论】:

    【解决方案2】:

    使用.items()

    prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
    for item,price in prices.items():
      print item # => "banana"
      print price # => 4
    

    它是一个字典,所以你使用键来获取值。

    prices["banana"] # => 4
    prices["apple"] # => 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多