python - 如何从字典中打印具有特定键的列表

标签 python python-3.x

目前,我正在尝试检查项目字典并通过它们检查值。如果该值大于 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 .

关于python - 如何从字典中打印具有特定键的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57239076/

相关文章:

python - 函数序列错误 (0) (SQLFetch) - SQL、Pyodbc

Python:打乱包含重复项的字符串数组,同时保持项目的分布

Python:如何在三个列表中找到共同的值

python - 从 CMYK 转换为 RGB

python - 为什么这个正则表达式不起作用?也许是因为双重回顾?

python - 使用 Python 自动化 Windows GUI 操作

python - DataFrame 应用并返回可变多行?

python - 使用Python直接向USB发送信号

python - 使用 ipywidgets 按钮返回 DataFrame

python - 如何在 SQLITE3 上关闭和删除数据库后再次打开数据库