python - 在嵌套字典中打印值问题
问题描述
我在 DEFAULTS 字典中有两个嵌套字典:一个称为 PASSWRD,它具有描述特定消息的对,另一个称为 COMMANDS,列出了我希望在我的程序中使用的命令,以及一些密钥对的简要说明。其中一个密钥对是“密码”,它被分配了一个数字。
现在,我正在尝试通过一个小循环,将“密码”密钥对值与 PASSWRD 上的值匹配。
当我尝试:
for command, stuff in DEFAULTS["COMMANDS"].items():
print(f"\nCommand: {command}")
print(f'{stuff["Definition"]}')
它很好地列出了所有命令和定义。当我添加以下行时问题开始:
print(f'{stuff["Password"]}')
它提供以下错误消息:KeyError: 'Password'
任何想法为什么会产生这个错误?
最后的想法是产生这样的东西:
print(DEFAULTS["PASSWRD"][DEFAULTS["COMMANDS"][{stuff}]["Password"]])
这是行不通的。然而,
print(DEFAULTS["PASSWRD"][DEFAULTS["COMMANDS"]["ZV"]["Password"]])
效果很好
您可以在下面找到 MWE。
DEFAULTS = {
"PASSWRD" : {
0 : "None",
1: "Requires standard password",
2: "Requires factory password",
},
"COMMANDS" : {
"ZS" : {
"Type" : "SETUP",
"Max Parameters Required" : 1,
"Parameters" : "[,n]",
"Definition" : "Set/Get Seeder delay",
"Password": 0
},
"ZV" : {
"Type" : "SETUP",
"Max Parameters Required" : 1,
"Parameters" : "[,n]",
"Definition" : "Set/Get Variable Sync delay",
"Password": 0
},
}
}
for command, stuff in DEFAULTS["COMMANDS"].items():
print(f"\nCommand: {command}")
print(f'{stuff["Definition"]}')
# print(f'{stuff["Password"]}')
print(DEFAULTS["PASSWRD"][DEFAULTS["COMMANDS"]["QD"]["Password"]])
解决方案
stuff
是COMMANDS
迭代中的当前字典,它不是任何东西的键。所以使用stuff["Password"]
从该字典中获取密码。
for command, stuff in DEFAULTS["COMMANDS"].items():
print(f"\nCommand: {command}")
print(f'{stuff["Definition"]}')
print(DEFAULTS["PASSWRD"][stuff["Password"]])
推荐阅读
- python - 如何在 xlrd 中获取行号并将其保存到变量中
- python - Crontab 中的 Python 脚本:rm:无法删除,没有这样的文件或目录
- c# - 如何声明包含具有 2 种数据类型的数组的列表?
- c++ - 根据模板是指针/引用还是无选择函数
- vue.js - vuex中的变异状态
- c++ - recvfrom() 没有收到任何 UDP 消息
- sqlite - sqlite3.exe Nuget 包安装失败 - .NET 框架兼容性?
- android - 我的第一个应用程序的横向/纵向方向:为什么会卡住?
- rest - Dialogflow 未通过上下文检测意图
- opayo - 5006:无法重定向到供应商网站。供应商未能提供重定向 URL。- PHP Inframe 集成