python - 如何从具有特定属性的字典中打印键列表
问题描述
目前,我正在尝试检查项目字典并通过它们检查值。如果该值大于 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 - 更新 QSqlRelationalTableModel 中的相关表
- javascript - 隐藏空标签如果它没有内容
- excel - 在 VBA 中使用集合和 V 类字典
- python - 在不安装的情况下导入 Python 库
- laravel - 使用具有表之间关系的 Eloquent 模型进行 CRUDE 操作
- c# - 使用 IIS 时未触发 CancellationToken
- javascript - 定期在网站上显示和更新来自 JSON-URL 的值
- c# - ASP NET Core SignalR 从另一个服务响应客户端
- twilio - Twilio Stream 仅在收到呼叫时
- python - TensorFlow 版本 2 和 BatchNorm 折叠中的量化感知训练