python - 循环遍历包含类的多个字典
问题描述
如何遍历包含类的多个字典。我真的不知道该怎么解释更多。如果您有任何问题,请在下方评论
class Stats:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
inte = {1: Stats(name='Programming', exp=0, description="This is a description"),
2: Stats(name='Reading', exp=0, description='Reading Description'),
3: Stats(name='Meditating', exp=0, description='Meditaing Description')}
stre = {1: Stats(name='Excercise', exp=0, description="This is a description"),
2: Stats(name='Gym', exp=0, description="Gym description")}
will = {1: Stats(name='Resistance', exp=0, description="This is a description"),
2: Stats(name='Chores', exp=0, description='Chores description')}
# Works with every single dictionary but how to do it with multiple?
for k, v in stre.items():
if v.name == "Excercise"
print("You did excercise")
有没有办法通过字典列表进行搜索?就像一次在他们三个中搜索,然后比较所有内容,然后如果有匹配项打印那里 exp?虽然我可以通过对每个字典进行编码来解决问题,但我相信有更优化和更有效的方法来做到这一点。谢谢你 :D
解决方案
我很确定您只需要创建字典的集合(列表)并循环它。像这样的东西:
traits = [inte, stre, will]
你如何循环它们取决于你。您可以使用嵌套的 for 循环来做到这一点:
for trait in traits:
for k, v in trait.items():
# checks and prints here
如果需要,您可以添加一些语法糖来节省一些缩进:
for k, v in [trait.items() for trait in traits]:
# checks and prints here
推荐阅读
- symfony - Symfony 3.4:您是否忘记了另一个命名空间的“使用”语句?
- akka-stream - Lagom 框架主题 Websocket 超时连接因错误而关闭
- oracle - LOCK 如何在 COMMIT 中存活,或者如何在没有 COMMIT 和丢失 LOCK 的情况下将 LOCKed 表的更改传播到另一个会话
- angular - Angular 6:当我尝试将对象传递给 dropData 时,它返回“[Object Object]”
- sharepoint - 如何使 ms-sharepoint-ribbon 适合移动视图?
- android - 使用 Recyclerview 中的 itemTouchHelper 在 cardview 上拖动高程翻译
- angular - 未检测到匹配的服务人员
- xml - 如何使用 XSLT 在 XML 节点中添加和删除项目
- android - Android 将 editText 的文本换行,该文本恰好在 textView 的右侧对齐
- angular - 我怎样才能获得我选择的选项的更多数据?