KeyError访问字典? [英] KeyError while accessing dictionary?

查看:204
本文介绍了KeyError访问字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面给出一个名为 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运行Node.js,
OptionSettings:[
{
命名空间:aws:ec2:vpc
OptionName:AssociatePublicIpAddr ess,
Value:true
},
{
Namespace:aws:elasticbeanstalk:environment,
OptionName
Value:LoadBalanced
},
{
命名空间:aws:ec2:vpc,
OptionName子网,
值:param1
},
{
命名空间:aws:autoscaling:launchconfiguration,
OptionName安全组,
值:param2
},
{
命名空间:aws:autoscaling:asg,
OptionName:MinSize,
Value:1
},
{
命名空间:aws:autoscaling:asg,
OptionName:MaxSize,
Value:4
},
{
命名空间:aws:autoscaling:asg,
OptionName:可用区域,
值:任何
},
{
命名空间:aws:autoscaling:asg,
OptionName:冷却,
值:360
},
{
命名空间:aws:autoscaling:launchconfiguration,
OptionName:IamInstanceProfile,
Value:NepRole
},
{
命名空间:aws:autoscaling:launchconfiguration,
OptionName:MonitoringInterval,
Value:5分钟
},
{
命名空间:aws:autoscaling:launchconfiguration,
OptionName:RootVolumeType,
Value:gp2
},
{
命名空间:aws:autoscaling:launchconfiguration,
选项名称:RootVolumeSize,
值:10
},
{
namespace:aws:elasticbeanstalk:sns:topics,
OptionName:Notification Endpoint,
Value:sunil.kumar2@pb.com
}
{
命名空间:aws:elasticbeanstalk:hostmanager,
OptionName:LogPublicationControl,
Value:false
}
{
Namespace:aws:elasticbeanstalk:command,
OptionName:DeploymentPolicy,
Value:滚动
}
{
命名空间:aws:elasticbeanstalk:command,
OptionName:BatchSizeType,
Value 百分比
},
{
命名空间:aws:elasticbeanstalk:command,
OptionName:BatchSize,
Value 100
},
{
命名空间:aws:elasticbeanstalk:command,
OptionName:HealthCheckSuccessThreshold,
Value OK
},
{
命名空间:aws:elasticbeanstalk:command,
OptionName:IgnoreHealthCheck,
Value false
},
{
命名空间:aws:elasticbeanstalk:command,
OptionName :超时,
值:600
},
{
命名空间:aws:autoscaling:updatepolicy:rollingupdate,
OptionName:RollingUpdateEnabled,
Value:false
},
{
命名空间:aws:ec2:vpc,
OptionName:ELBSubnets,
Value:param3
},
{
命名空间:aws:elb:loadbalancer,
OptionName:SecurityGroups,
Value:param4
},
{
命名空间:aws:elb:loadbalancer,
OptionName:ManagedSecurityGroup,
Value:param4
}
]

}
/ pre>

解决方案

不幸的是你不能这样做。



当您键入 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
在list_of_params中的elem:
_ = _ [elem]
return _

我没有测试,但它应该可以正常工作。

(另外,这只是一个引导您完成替代解决方案的演示)


I have a dictionary named json_dict given below.

I need to access the element ==> json_dict['OptionSettings'][3]['Value'].

I need to access the element using the syntax

print(json_dict[parameter]).

When I give a parameter such as

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

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

I am getting an error like the one below:

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

I tried to use the below solution but it just printed a string

str1="json_dict"
print(str1+param)

Full Dictionary below:

{
        "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"
                            }
                           ]

}

解决方案

Unfortunately you can't do that.

When you type param="['OptionSettings'][3]['Value']" and then json_dict[param], you are basically asking for the value represented by the key "['OptionSettings'][3]['Value']" which does not exists.

You´ll have to navigate through the levels until you get to the last one.


But of course, if you need a one-liner, you can always create some logic and extract that to a method.

For example, instead of

print(json_dict[param]). 

you could use something like

print(get_json_value(json_dict, param))

and define a function such as

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 _

I haven't tested it but it should work fine.
(Also, it is just a demo made to guide you through an alternate solution)

这篇关于KeyError访问字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆