[英]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()])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.