簡體   English   中英

Python迭代字典

[英]Python iterate over a dictionary

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)

在Python 2中你會做:

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

在Python 3中,使用items()代替( iteritems()已被刪除):

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

教程將介紹這一點。

更改

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)

通常情況下,如果你遍歷一個字典,它只會返回一個鍵,所以這就是它錯誤地說“解壓縮的值太多”的原因。 相反, itemsiteritems將返回key value pair list of tuplesiterator以迭代key and values

或者,您始終可以通過鍵訪問該值,如以下示例所示

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

for key in mydict遍歷鍵。 您想要迭代項目:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM