访问字典时的KeyError?

时间:2016-08-30 14:01:12

标签: python json python-2.7 python-3.x dictionary

我有一个名为json_dict的字典,如下所示。

我需要访问元素==> json_dict['OptionSettings'][3]['Value']

我需要使用语法

访问该元素

print(json_dict[parameter])

当我提供诸如

之类的参数时

param="['OptionSettings'][3]['Value']"

param="'OptionSettings'][3]['Value']"

我收到如下错误:

KeyError: "['OptionSettings'][3]['Value']"

我尝试使用以下解决方案,但它只打印了一个字符串

str1="json_dict"
print(str1+param)

下面的完整词典:

{
        "ApplicationName": "Test",
        "EnvironmentName": "ABC-Nodejs",
        "CNAMEPrefix": "ABC-Neptune",
        "SolutionStackName": "64bit Amazon Linux 2016.03 v2.1.1 running Node.js",
        "OptionSettings": [
                           {
                            "Namespace": "aws:ec2:vpc",
                            "OptionName": "AssociatePublicIpAddress",
                            "Value": "true"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:environment",
                            "OptionName": "EnvironmentType",
                            "Value": "LoadBalanced"
                            },
                           {
                            "Namespace": "aws:ec2:vpc",
                            "OptionName": "Subnets",
                            "Value": "param1"
                            },
                           {
                            "Namespace": "aws:autoscaling:launchconfiguration",
                            "OptionName": "SecurityGroups",
                            "Value": "param2"
                            },
                           {
                            "Namespace": "aws:autoscaling:asg",
                            "OptionName": "MinSize",
                            "Value": "1"
                            },
                           {
                            "Namespace": "aws:autoscaling:asg",
                            "OptionName": "MaxSize",
                            "Value": "4"
                            },
                           {
                            "Namespace": "aws:autoscaling:asg",
                            "OptionName": "Availability Zones",
                            "Value": "Any"
                            },
                           {
                            "Namespace": "aws:autoscaling:asg",
                            "OptionName": "Cooldown",
                            "Value": "360"
                            },
                           {
                            "Namespace": "aws:autoscaling:launchconfiguration",
                            "OptionName": "IamInstanceProfile",
                            "Value": "NepRole"
                            },
                           {
                            "Namespace": "aws:autoscaling:launchconfiguration",
                            "OptionName": "MonitoringInterval",
                            "Value": "5 minutes"
                            },
                           {
                            "Namespace": "aws:autoscaling:launchconfiguration",
                            "OptionName": "RootVolumeType",
                            "Value": "gp2"
                            },
                           {
                            "Namespace": "aws:autoscaling:launchconfiguration",
                            "OptionName": "RootVolumeSize",
                            "Value": "10"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:sns:topics",
                            "OptionName": "Notification Endpoint",
                            "Value": "sunil.kumar2@pb.com"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:hostmanager",
                            "OptionName": "LogPublicationControl",
                            "Value": "false"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:command",
                            "OptionName": "DeploymentPolicy",
                            "Value": "Rolling"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:command",
                            "OptionName": "BatchSizeType",
                            "Value": "Percentage"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:command",
                            "OptionName": "BatchSize",
                            "Value": "100"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:command",
                            "OptionName": "HealthCheckSuccessThreshold",
                            "Value": "Ok"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:command",
                            "OptionName": "IgnoreHealthCheck",
                            "Value": "false"
                            },
                           {
                            "Namespace": "aws:elasticbeanstalk:command",
                            "OptionName": "Timeout",
                            "Value": "600"
                            },
                           {
                            "Namespace": "aws:autoscaling:updatepolicy:rollingupdate",
                            "OptionName": "RollingUpdateEnabled",
                            "Value": "false"
                            },
                           {
                            "Namespace": "aws:ec2:vpc",
                            "OptionName": "ELBSubnets",
                            "Value": "param3"
                            },
                           {
                            "Namespace": "aws:elb:loadbalancer",
                            "OptionName": "SecurityGroups",
                            "Value": "param4"
                            },
                           {
                            "Namespace": "aws:elb:loadbalancer",
                            "OptionName": "ManagedSecurityGroup",
                            "Value": "param4"
                            }
                           ]

}

2 个答案:

答案 0 :(得分:2)

不幸的是你做不到。

当您键入param="['OptionSettings'][3]['Value']"然后json_dict[param]时,您基本上要求键"['OptionSettings'][3]['Value']"所代表的值不存在。

你必须浏览关卡才能到达最后一层。

但是,当然,如果您需要单行,您可以随时创建一些逻辑并将其提取到方法中。

例如,而不是

print(json_dict[param]). 

你可以使用像

这样的东西
print(get_json_value(json_dict, param))

并定义一个函数,如

import re

def get_json_value(json_dict, params):
    list_of_params = re.findall(r'\[([^]]*)\]', params)
    #list_of_params = ['OptionSettings', '3', 'Value']

    _ = json_dict
    for elem in list_of_params:
         _ = _[elem]
    return _

我没有测试过,但它应该可以正常工作。
(此外,它只是一个演示来指导您完成备用解决方案)

答案 1 :(得分:-1)

这对我有用

str1="json_dict"
params="['OptionSettings'][3]['Value']"
str2=str1+params
print(eval(str5))

此处使用函数 eval() 是解决此问题的关键。