如何将 json "dict" 更改为 aws boto3 标签集字典列表的可使用格式

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

我有一个 JSON 文件,其中包含以下格式的标签集(键、值):

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

boto3 S3 put_bucket_tagging操作需要获取如下格式的tagset:

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

它看起来像一个字典列表,但我不知道如何到达那里。我试过:

    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()

这导致:

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

'Value': 'Key1''Value': 'Key2' 显然是错误的,因为它们需要是值。

我知道我代码中的 "value": data[key] 部分不正确,但我不知道如何从标签集中的值中的 json 获取“值”。此外,我不知道我使用 for 循环的方法是否完全正确,这对我来说感觉有点奇怪。我不拘泥于 for 循环方法,欢迎从 json 到标签集的任何其他建议。

您可以使用 .items():

在迭代中同时获取键和值
content=[]
for k,v in data.items():    
    content.append({"Key":k, "Value":v})
mynewtagset = "'Tagset': "+ str(content)

如果你喜欢玩代码高尔夫,你也可以使用列表理解来做到这一点:

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