首页 > 解决方案 > 循环遍历包含类的多个字典

问题描述

如何遍历包含类的多个字典。我真的不知道该怎么解释更多。如果您有任何问题,请在下方评论

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

标签: pythonpython-3.x

解决方案


很确定您只需要创建字典的集合(列表)并循环它。像这样的东西:

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

推荐阅读