如何检查python字典中的变量?

2024-09-30 18:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个从字典中显示并显示选项的项目。我想根据你的选择隐藏一些,否则会造成冗余。 示例代码:

scenes = {
   "scene": {
      "description": "The text displayed",
   "paths": [
      { "go_to": "scene2", "phrase": "Proceed to scene 2", scene2seen:True },
      { "go_to": "scene2alt", "phrase": "Only shows if scene2seen is true", if scene2seen:True }
]
}
}

预期产量:

The text displayed.
 1 Proceed to scene 2

在选择第一个选项之前,不会显示另一个选项

对变量的第二个调用抛出语法错误,我尝试了几种不同的方法。有人能帮忙吗?你知道吗


Tags: theto项目texttruego示例if
2条回答

您可以像这样访问每个键的值:key['value']

因此,如果要获取第一条路径的值,可以编写'scenes['scene']['paths'][0]。你知道吗

您还可以循环使用dict以根据需要生成值:

for k, v in scenes.items(): print(k, v)

这能回答你的问题吗?你知道吗

如果您想动态创建词典,如果我正确理解了您的问题,它可以这样工作:

{ (your_key if condition else default_key):(value_if_true if condition 
          else value_if_false) for key, value in dict_.items() }

或者如果你能让你的问题更容易理解,那就更好了。你知道吗

相关问题 更多 >