Python lists and dictionaries indexing

Viewed 12

In the AWS API documentation it wants me to call a function in the boto3 module like this:

response = client.put_metric_data(
    Namespace='string',
    MetricData=[
        {
            'MetricName': 'string',
            'Dimensions': [
                {
                    'Name': 'string',
                    'Value': 'string'
                },
            ],
            'Timestamp': datetime(2015, 1, 1),
            'Value': 123.0,
            'StatisticValues': {
                'SampleCount': 123.0,
                'Sum': 123.0,
                'Minimum': 123.0,
                'Maximum': 123.0
            },
            'Values': [
                123.0,
            ],
            'Counts': [
                123.0,
            ],
            'Unit': 'Seconds'|'Microseconds'|'Milliseconds'|'Bytes'|'Kilobytes'|'Megabytes'|'Gigabytes'|'Terabytes'|'Bits'|'Kilobits'|'Megabits'|'Gigabits'|'Terabits'|'Percent'|'Count'|'Bytes/Second'|'Kilobytes/Second'|'Megabytes/Second'|'Gigabytes/Second'|'Terabytes/Second'|'Bits/Second'|'Kilobits/Second'|'Megabits/Second'|'Gigabits/Second'|'Terabits/Second'|'Count/Second'|'None',
            'StorageResolution': 123
        },
    ]
)

So, I set a variable using the same format:

cw_metric = [
    {
        'MetricName': '',
        'Dimensions': [
            {
                'Name': 'Protocol',
                'Value': 'SSH'
            },
        ],
        'Timestamp': '',
        'Value': 0,
        'StatisticValues': {
            'SampleCount': 1,
            'Sum': 0,
            'Minimum': 0,
            'Maximum': 0
        }
    }
]

To my untrained eye, this looks simply like json and I am able to use json.dumps(cw_metric) to get a JSON formatted string output that looks, well, exactly the same.

But, apparently, in Python, when I use brackets I am creating a list and when I use curly brackets I am creating a dict. So what did I create above? A list of dicts or in the case of Dimensions a list of dicts with a list of dicts? Can someone help me to understand that?

And finally, now that I have created the cw_metric variable I want to update some of the values inside of it. I've tried several combinations. I want to do something like this:

cw_metric['StatisticValues']['SampleCount']=2

I am of course told that I can't use a str as an index on a list.

So, I try something like this:

cw_metric[4][0]=2

or

cw_metric[4]['SampleCount']=2

It all just ends up in errors.

I found that this works: cw_metric[0]['StatisticValues']['SampleCount']=2

But, that just seems stupid. Is this the proper way to handle this?

1 Answers

cw_metric is a list of one dictionary. Thus, cw_metric[0] is that dictionary. cw_metric[0]['Dimensions'] is a list of one dictionary as well. cw_metric[0]['StatisticValues'] is just a dictionary. One of its elements is, for example, cw_metric[0]['StatisticValues']['SampleCount'] == 1.

Related