【问题标题】:looping a unnamed dictionary in python在python中循环一个未命名的字典
【发布时间】:2012-04-11 07:57:12
【问题描述】:

有没有办法在 python 中同时打印匿名字典的键和值。

for key in {'one':1, 'two':2, 'three':3}:
    print key, ":", #value

【问题讨论】:

  • 那是dictionary,不是list
  • 谢谢大家。我的意思是说字典。不小心将其输入为列表。
  • 为什么不使用元组列表来代替?

标签: python for-loop


【解决方案1】:
for key, value in {'one':1, 'two':2, 'three':3}.iteritems():
    print key, ":", value

默认情况下,迭代它会返回它的键。 .iteritems() 返回 (key, value) 的 2 元组。

【讨论】:

    【解决方案2】:

    你可以这样做:

    for  (key, value) in {'one':1, 'two':2, 'three':3}.items():
        print key, value
    

    【讨论】:

      【解决方案3】:

      要遍历键/值对,您可以使用.items().iteritems()

      for k, v in {'one':1, 'two':2, 'three':3}.iteritems():
          print '%s:%s' % (k, v)
      

      http://docs.python.org/library/stdtypes.html#dict.iteritems

      【讨论】:

        【解决方案4】:

        当然,只需使用:

        for key,value in {'one':1, 'two':2, 'three':3}.items():
            print key, ":", value
        

        【讨论】:

          【解决方案5】:

          你可以使用iteritems方法来遍历dict

          for key, value in {'one':1, 'two':2, 'three':3}.iteritems():
              print key
              print value
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-09-17
            • 2023-02-21
            • 2018-02-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-06
            相关资源
            最近更新 更多