七度&光 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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序