【发布时间】:2021-12-11 03:03:44
【问题描述】:
我在 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"]])
【问题讨论】:
标签: python dictionary for-loop