how can I change json "dict" into a consumable format for aws boto3 tagset list of dicts

I have a JSON file that contains a tagset (key, values) in the following format:

{"Key1":"ValueA", "Key2":"ValueB"}

The boto3 S3 put_bucket_tagging operation needs to get the tagset in the following format:

'TagSet': [
            {
                'Key': 'Key1',
                'Value': 'ValueA',
            },
            {
                'Key': 'Key2',
                'Value': 'ValueB',
            }
        ]

It looks like a list of dicts, but I don’t know how to get there. I have tried:

    def reformat_json_tagset():
    
        with open('tagset.json') as json_file:
                data = json.load(json_file)
    
    
        info = {}
        content = []
    
        for key in data:
            info = {
                "Key": data[key],
                "Value": data[key],
            }
            content.append(info)
    
        mynewtagset = print("'Tagset': "+ str(content))
        return(mynewtagset)
    
    reformat_json_tagset()

which results in:

'Tagset': [{'Key': 'Key1', 'Value': 'Key1'}, {'Key': 'Key2', 'Value': 'Key2'}

'Value': 'Key1' and 'Value': 'Key2' are obviously wrong, as they need to be the values.

I understand that the "value": data[key] part in my code is not correct but I don’t know how to get the "values" from the json in the values from the tagset. Also I don’t know if my approach with the for loop is at all correct, it feels a bit weird to me. I’m not stuck to the for loop method, any other suggestion to get from the json to the tagset is more than welcome.

>Solution :

You can get both the key and the value in your iteration by using .items():

content=[]
for k,v in data.items():    
    content.append({"Key":k, "Value":v})
mynewtagset = "'Tagset': "+ str(content)

You could also do this using list comprehension if you like to play code golf:

mynewtagset="'Tagset': "+str([{"Key":k, "Value":v} for k, v in data.items()])

Leave a Reply