![](/img/trans.png)
[英]How to create a dictionary from a list of dictionary using specific keys in Python
[英]How to print a list of keys from a dictionary with a specific
目前我正在嘗試檢查項目字典並通過它們檢查值。 如果該值大於 0,則將其打印在列表中,否則將其忽略並繼續。 目前我輸入了這個代碼:
from items import items
for item in items:
if items[item][6] < 0:
print("You have ", item[6], " of ", item[0], " .")
但是從這里開始,我對如何繼續進行此操作感到非常困惑。 我收到一個索引錯誤,但我不確定它的用途。
您正在迭代字典,其中鍵是項目的名稱,值是一個包含一些信息的元組。
您可以這樣做 注意這僅在您的元組始終具有相同的結構/字段數時才有效。
In [23]: my_items = {'Broken Watch': ('Broken Watch', 'This is a watch. It appears to be shattered, and the hands are no longer moving.', 'Item', 'Junk', 1, 1, 0), 'Watch that will
...: print': ('Some stuff', 'More stuff', 'Item', 'Junk', 1, 1, 7)}
In [24]: for name, info in my_items.items():
...: num= info[6]
...: print("Checking num", num)
...: if num > 0:
...: print("You have", num, "of", name, ".")
...:
...:
...:
Checking num 0
Checking num 7
You have 7 of Watch that will print .
您沒有正確訂閱item
。 item
是items
一個鍵,你必須與它相關聯(就像你在if
語句中所做的那樣)。 另請注意,根據問題的文本,您可能打算使用>
運算符,而不是<
:
for item in items:
if items[item][6] > 0:
print("You have ", items[item][6], " of ", items[item][0], " .")
作為旁注,您需要的所有值似乎都在值元組中,因此您可以迭代這些值而不是使用鍵來訪問它們:
for item in items.values():
if item[6] > 0:
print("You have ", item[6], " of ", item[0], " .")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.