Python iterate over a dictionary

后端 未结 3 1661
庸人自扰
庸人自扰 2020-12-11 04:28
In [26]: test = {}

In [27]: test[\"apple\"] = \"green\"

In [28]: test[\"banana\"] = \"yellow\"

In [29]: test[\"orange\"] = \"orange\"

In [32]: for fruit, colour          


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 05:02

    In Python 2 you'd do:

    for fruit, color in test.iteritems():
        # do stuff
    

    In Python 3, use items() instead (iteritems() has been removed):

    for fruit, color in test.items():
        # do stuff
    

    This is covered in the tutorial.

提交回复
热议问题