首页 > 解决方案 > 如何从具有特定属性的字典中打印键列表

问题描述

目前,我正在尝试检查项目字典并通过它们检查值。如果该值大于 0,则将其打印在列表中,否则将其忽略并继续。目前我已经输入了这个代码:

from items import items

for item in items:
    if items[item][6] < 0:
        print("You have ", item[6], " of ", item[0], " .")

但是从这里我很困惑如何继续这个。我收到一个索引错误,但我不确定它的用途。

标签: pythonpython-3.x

解决方案


您正在迭代一个字典,其中键是项目的名称,值是一个包含一些信息的元组。

你可以这样做 注意这只有在你的元组总是具有相同的结构/字段数时才有效。

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 .

推荐阅读