笑故挽风 2010-07-20 22:27 采纳率: 100%
浏览 1349
已采纳

使用 for 循环遍历字典

I am a bit puzzled by the following code:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    print key, 'corresponds to', d[key]

What I don't understand is the key portion. How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?

转载于:https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops

  • 写回答

11条回答 默认 最新

  • derek5. 2010-07-20 22:29
    关注

    key is just a variable name.

    for key in d:
    

    will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

    For Python 2.x:

    for key, value in d.iteritems():
    

    For Python 3.x:

    for key, value in d.items():
    

    To test for yourself, change the word key to poop.

    For Python 3.x, iteritems() has been replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

    The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏