簡體   English   中英

如何遍歷字典中的列表

[英]How to iterate through a list in a dictionary

如果我想打印:紅色襯衫藍色襯衫黑色牛仔褲等等。我有這個代碼:

wardrobe = {"shirt": ["red", "blue", "white"], "jeans":["blue", "black"]}
for shirts in wardrobe.keys():
   for colors in shirts:
      print("{} {}".format(colors, shirts))

我得到:s shirt h shirt i shirt 等等......

有人建議嗎? 謝謝!

我的建議是使用允許您逐行調試和運行的 IDE。 這將幫助你更好地理解你的代碼在做什么。

但是你想要這樣做的方法是使用.items()來遍歷字典的鍵和值。 該值是您的顏色列表,因此請遍歷該列表。

wardrobe = {"shirt": ["red", "blue", "white"], "jeans":["blue", "black"]} 
            
for article, color_list in wardrobe.items(): 
    for color in color_list:
        print("{} {}".format(color, article))

正如您所做的那樣,使用兩個嵌套循環,但請確保在內部循環中您正在迭代值,而不是鍵。 迭代items()會給你鍵和值作為兩個不同的變量,這很容易:

>>> wardrobe = {"shirt": ["red", "blue", "white"], "jeans":["blue", "black"]}
>>> for article, colors in wardrobe.items():
...     for color in colors:
...         print(f"{color} {article}")
...
red shirt
blue shirt
white shirt
blue jeans
black jeans

您需要遍歷鍵和值,因此在 Python 3 中,您可以使用此處所述的.items()方法。

要正確迭代每個服裝項目的顏色,您需要迭代項目,然后是列表中的每種顏色。 這樣的事情應該讓你接近:

wardrobe = {"shirt": ["red", "blue", "white"], "jeans":["blue", "black"]}
for item, colors in wardrobe.items():
   for color in colors:
      print(color, item)

red shirt
blue shirt
white shirt
blue jeans
black jeans

你嘗試的整體邏輯是值得稱道的。

> wardrobe = {"shirt": ["red", "blue", "white"], "jeans":["blue", "black"]}
> for shirts in wardrobe.keys():
>    for colors in shirts:
>        print("{} {}".format(colors, shirts))

但是你所做的是你正在迭代字典的鍵,而不是它的項目。

答案是

wardrobe = {"shirt": ["red", "blue", "white"], "jeans":["blue", "black"]}
for dict_keys,dict_values in wardrobe.items():
    for colors in dict_values:
       print("{} {}".format(colors, dict_keys))

字典有 3 種內置方法可以幫助您在字典中進行迭代。

  1. dict.keys()
  2. dict.values()
  3. dict.items()

dict.keys() 返回字典中所有鍵的列表。

dict.values() 返回所有值的列表。

dict.items() 返回所有項目的列表。 items 是與值關聯的鍵列表。

warddrobe={"shirt":["white","red","green"],"jeans":["black","blue"]}
for shirt in warddrobe["shirt"]:
    print(f"{shirt} shirt")
for jeans in warddrobe["jeans"]:
    print(f"{jeans} jeans")

    ```
`
white shirt
red shirt
green shirt
black jeans
blue jeans
`
`
you just have to grab values thruogh indexing then simply print .
you need to use two for loop for it.
`
    
>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> for key in a_dict:
...     print(key)

這將打印 color 、 fruit 和 pet 因為它只遍歷字典中的鍵。 祝你今天過得愉快

暫無
暫無

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

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