首页 > 解决方案 > 在嵌套字典中打印值问题

问题描述

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

标签: pythondictionaryfor-loop

解决方案


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

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

演示


推荐阅读