Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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()])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading