2011-12-21 19 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 

Quello che voglio è iterare sul test e ottenere la chiave e il valore insieme. Se faccio solo un for item in test:, ottengo solo la chiave.Python iterate su un dizionario

Un esempio di obiettivo finale sarebbe:

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

veda 'help (dict)' – u0b34a0f6ae

+0

Perché non 'per la frutta in prova: print "Il frutto% s è il colore% s "% (frutta, prova [frutto])'? – mtrw

risposta

13

In Python 2 faresti:

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

In Python 3, utilizzare items() invece (iteritems() è stata rimossa):

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

Questo è coperto in the tutorial.

+1

In Python 3, dovrai cambiare 'itemiter()' a 'item()' 'per fruit, color in test.items()' - poiché dict.iteritems() è stato rimosso e ora dict.items() la stessa cosa –

+0

@ user-asterix Grazie, ho aggiornato la risposta per chiarire che. –

4

Il normale for key in mydict itera sui tasti. Si vuole iterare elementi:

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

Modifica

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, se eseguire iterazioni su una dizionario tornerà solo chiave, quindi quella era la ragione per cui sbagliava o-out dicendo "Troppi valori da decomprimere". Invece items o iteritems restituirebbe un list of tuples di key value pair o un iterator per iterare su key and values.

In alternativa si può sempre accedere al valore tramite chiave come nel seguente esempio

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