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

Điều tôi muốn là lặp lại kiểm tra và lấy khóa và giá trị cùng nhau. Nếu tôi chỉ làm một số for item in test:, tôi chỉ nhận được chìa khóa.Python lặp qua một từ điển

Một ví dụ về mục tiêu cuối cùng sẽ là:

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

thấy 'sự giúp đỡ (dict) ' – u0b34a0f6ae

+0

Tại sao không' cho hoa quả trong thử nghiệm: print "Quả% s là màu% s "% (trái cây, thử nghiệm [trái cây])'? – mtrw

Trả lời

13

Trong Python 2 bạn muốn làm:

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

Trong Python 3, sử dụng items() thay vì (iteritems() đã được gỡ bỏ):

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

Điều này được bao gồm trong the tutorial.

+1

Trong Python 3, bạn sẽ phải thay đổi 'itemiter()' thành 'item()' 'cho trái cây, màu trong test.items()' - kể từ dict.iteritems() đã bị loại bỏ và bây giờ dict.items() làm cùng một điều –

+0

@ user-asterix Cảm ơn, tôi đã cập nhật câu trả lời để làm rõ điều đó. –

4

Thông thường for key in mydict lặp qua các phím. Bạn muốn lặp mục:

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

Thay đổi

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) 

hoặc

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

Thông thường, nếu bạn lặp qua một cuốn từ điển nó chỉ sẽ trả về một chính, đó là lý do nó sai or-ed out nói "Quá nhiều giá trị để giải nén". Thay vào đó, items hoặc iteritems sẽ trả lại một list of tuples của key value pair hoặc iterator để lặp qua key and values.

Hoặc bạn luôn có thể truy cập vào các giá trị thông qua chủ chốt như trong ví dụ sau

for fruit in test: 
    print "The fruit %s is the colour %s" % (fruit, test[fruit]) 
Các vấn đề liên quan