在嵌套字典中打印值有问题



我在DEFAULTS字典中有两个嵌套字典:一个叫做PASSWRD,它有描述特定消息的对,另一个叫做COMMANDS,列出我希望在程序中使用的命令,以及对一些键对的简要描述。其中一个密钥对是"密码",它被分配了一个数字。

现在,我试着通过一个小循环来匹配"Password">

当我尝试:

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"]]) 

stuffCOMMANDS迭代中的当前字典,它不是任何东西的键。因此,使用stuff["Password"]从该字典中获取密码。

for command, stuff in DEFAULTS["COMMANDS"].items():
print(f"nCommand: {command}")
print(f'{stuff["Definition"]}')
print(DEFAULTS["PASSWRD"][stuff["Password"]]) 

演示