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

जो मैं चाहता हूं वह परीक्षण पर पुनरावृत्ति करना और कुंजी और मूल्य एक साथ प्राप्त करना है। अगर मैं सिर्फ for item in test: करता हूं तो मुझे केवल कुंजी मिलती है।पाइथन फिर से एक शब्दकोश

अंतिम लक्ष्य का एक उदाहरण होगा:

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

देख 'मदद (dict) में के रूप में उपयोग कर सकते हैं' – u0b34a0f6ae

+0

क्यों नहीं 'में परीक्षण फल के लिए: प्रिंट" फल% s रंग% है एस "% (फल, परीक्षण [फल])'? – mtrw

उत्तर

13

अजगर 2 में आप कर चाहते हैं:

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

अजगर 3 में, बजाय items() का उपयोग करें (iteritems() हटा दिया गया है):

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

यह the tutorial में शामिल है।

+1

पायथन 3 में, आपको फल के लिए 'itemiter()' 'item()' 'को बदलना होगा, test.items() में रंग- - क्योंकि dict.iteritems() को हटा दिया गया था और अब dict.items() करता है वही बात –

+0

@ उपयोगकर्ता-एस्टेरिक्स धन्यवाद, मैंने इसे स्पष्ट करने के लिए उत्तर अपडेट किया है। –

4

सामान्य for key in mydict कुंजी पर पुनरावृत्त करता है।

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

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

या

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

आम तौर पर करने के लिए, यदि आप एक शब्दकोश से अधिक पुनरावृति यह केवल एक वापस आ जाएगी

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

बदलें: आप आइटम पुनरावृति करना चाहते हैं कुंजी, तो यही कारण है कि यह गलती है कहें "अनपैक करने के लिए बहुत सारे मूल्य" कह रहे हैं। इसके बजाय items या iteritems के list of tuples या key and values पर पुनरावृत्त करने के लिए iterator लौटाएगा।

वैकल्पिक रूप से आप हमेशा मूल्य कुंजी के माध्यम से निम्न उदाहरण

for fruit in test: 
    print "The fruit %s is the colour %s" % (fruit, test[fruit]) 
संबंधित मुद्दे