七度&光 2010-07-20 22:27 采纳率: 22.2%
浏览 2233
已采纳

使用 for 循环遍历字典产生的疑问

下面的代码让我有点困惑:

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

我对key部分不是很理解。Python 如何识别它只需要从字典中读取密钥?在 Python 中,key 是一个特殊的单词吗? 还是仅仅是一个变量?

  • 写回答

11条回答 默认 最新

  • python小菜 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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器