[英]Python 3.8 - Unable to update dictionary
您好,我有下面这本字典,我想更新
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":"arn:aws:iam::111111111111:saml-provider/Test"
},
"Action":"sts:AssumeRoleWithSAML",
"Condition":{
"StringEquals":{
"SAML:aud":"https://signin.aws.amazon.com/saml"
}
}
}
]
}
想更新到
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":[
"arn:aws:iam::111111111111:saml-provider/Test",
"arn:aws:iam::111111111111:saml-provider/Test2"
]
},
"Action":"sts:AssumeRoleWithSAML",
"Condition":{
"StringEquals":{
"SAML:aud":"https://signin.aws.amazon.com/saml"
}
}
}
]
}
即将“arn:aws:iam::111111111111:saml-provider/Test2”添加到“Federated”并使其成为一个列表。 下面是我的代码
new_arn = "arn:aws:iam::111111111111:saml-provider/Test2"
my_dict = {
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":[
"arn:aws:iam::111111111111:saml-provider/Test",
]
},
"Action":"sts:AssumeRoleWithSAML",
"Condition":{
"StringEquals":{
"SAML:aud":"https://signin.aws.amazon.com/saml"
}
}
}
]
}
for b in my_dict['Statement']:
updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
b['Principal']['Federated']: updated_arn
print(my_dict)
我对 python 有点陌生,我不确定我做错了什么字典没有更新。 有人可以就我可能做错的事情提供一些指导吗
正如人们评论的那样,您正在构建一个看起来像列表的字符串:
for b in my_dict['Statement']:
updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
b['Principal']['Federated']: updated_arn
您可以改为创建一个真实列表:
for b in my_dict['Statement']:
updated_arn = [b['Principal']['Federated'], new_arn]
b['Principal']['Federated'] = updated_arn
# note it's `=` not `:` here
编辑:如果Federated
有时是一个字符串,有时已经是一个列表,您需要检查它的类型并采取相应的行动:
for b in my_dict['Statement']:
federated = b['Principal']['Federated']
if isinstance(federated, list):
federated.append(new_arn)
# (which updates the list within the dict, no need to assign back to the dict)
else:
b['Principal']['Federated'] = [federated, new_arn]
您可以将 append 设为“Federated”的当前值,如下所示:
for b in my_dict['Statement']:
b['Principal']['Federated'].append(new_arn)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.