2011-12-21 23 views
5
In [26]: test = {} 

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

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

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

In [32]: for fruit, colour in test: 
    ....:  print fruit 
    ....:  
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
/home1/users/joe.borg/<ipython-input-32-8930fa4ae2ac> in <module>() 
----> 1 for fruit, colour in test: 
     2  print fruit 
     3 

ValueError: too many values to unpack 

Lo que quiero es iterar sobre la prueba y obtener la clave y el valor juntos. Si solo hago un for item in test: obtengo la clave solamente.Python iterar sobre un diccionario

Un ejemplo de la meta final sería:

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

ver'ayuda (dict) ' – u0b34a0f6ae

+0

Por qué no' para la fruta en la prueba: print "El fruto% s es el color% s "% (fruta, prueba [fruta]) '? – mtrw

Respuesta

13

En Python 2 Harías:

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

En Python 3, use items() lugar (iteritems() se ha eliminado):

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

Esto se cubre en the tutorial.

+1

En Python 3, tendrá que cambiar 'itemiter()' a 'item()' 'para fruit, color en test.items()' - ya que dict.iteritems() se eliminó y ahora dict.items() lo hace lo mismo –

+0

@ user-asterix Gracias, he actualizado la respuesta para aclarar eso. –

4

La normal for key in mydict itera sobre las teclas. ¿Quieres recorrer artículos:

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

Cambio

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

a

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

o

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

Normalmente, si iterar sobre un diccionario que sólo devolverá una clave, entonces esa fue la razón por la que erró or-ed out diciendo "Demasiados valores para desempaquetar". En su lugar items o iteritems devolvería un list of tuples de key value pair o un iterator para iterar sobre el key and values.

alternativa siempre se puede acceder al valor a través de tecla que en el ejemplo siguiente

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