Python iterate over a dictionary

后端 未结 3 1637
庸人自扰
庸人自扰 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.

    0 讨论(0)
  • 2020-12-11 05:07

    Change

    for fruit, colour in test:
        print "The fruit %s is the colour %s" % (fruit, colour)
    

    to

    for fruit, colour in test.items():
        print "The fruit %s is the colour %s" % (fruit, colour)
    

    or

    for fruit, colour in test.iteritems():
        print "The fruit %s is the colour %s" % (fruit, colour)
    

    Normally, if you iterate over a dictionary it will only return a key, so that was the reason it error-ed out saying "Too many values to unpack". Instead items or iteritems would return a list of tuples of key value pair or an iterator to iterate over the key and values.

    Alternatively you can always access the value via key as in the following example

    for fruit in test:
        print "The fruit %s is the colour %s" % (fruit, test[fruit])
    
    0 讨论(0)
  • 2020-12-11 05:14

    The normal for key in mydict iterates over keys. You want to iterate items:

    for fruit, colour in test.iteritems():
        print "The fruit %s is the colour %s" % (fruit, colour)
    
    0 讨论(0)
提交回复
热议问题