Error while accessing dictionary in python
<p>I have a dictionary named <code>json_dict</code> given below. </p>

<p>I need to access the element <code>==&gt; json_dict['OptionSettings'][3]['Value']</code>.</p>

<p>I need to access the element using the syntax</p>

<p><code>print(json_dict[parameter])</code>. </p>

<p>When I give a parameter such as</p>

<p><code>param="['OptionSettings'][3]['Value']"</code>  or</p>

<p><code>param="'OptionSettings'][3]['Value']"</code></p>

<p>I am getting an error like the one below:</p>

<p><code>KeyError: "['OptionSettings'][3]['Value']"</code>.</p>

<p>I tried to use the below solution but it just printed a string</p>

<pre><code>str1="json_dict"
print(str1+param)
</code></pre>

<p>Full Dictionary below:</p>

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

}
</code></pre>

<p>Unfortunately you can't do that. </p>

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

<p>YouÂ´ll have to navigate through the levels until you get to the last one.</p>

<hr>

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

<p>For example, instead of </p>

<pre><code>print(json_dict[param]). 
</code></pre>

<p>you could use something like</p>

<pre><code>print(get_json_value(json_dict, param))
</code></pre>

<p>and define a function such as </p>

<pre><code>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 _
</code></pre>

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

python json python-2.7 python-3.x dictionary