无法从字典中获取值

时间:2019-03-07 22:44:43

标签: python dictionary lambda

我正在尝试遍历字典并获取键“ PolicyName”的所有值。这是我的代码:

if (str(account_id)== "010123456"):
                    client = boto3.client('iam', region_name='us-east-1')
                    roles = client.list_roles()
                    attached_policy_dict = client.list_attached_role_policies(RoleName='sf-someRoleName')
                    attached_policy = json.dumps(attached_policy_dict)
                    for k,v in attached_policy_dict.items():
                        print(['AttachedPolicies']['PolicyName'])
                        # I also tried
                        print['PolicyName']

    attached_policy_dict = {
      "AttachedPolicies": [
        {
          "PolicyName": "sfDenyNetworkActions",
          "PolicyArn": "arn:aws:iam::56012365:policy/sfDenyNetworkActions"
        },
        {
          "PolicyName": "sf-csdc-developer-policy",
          "PolicyArn": "arn:aws:iam::563012454:policy/sf-policyname"
        }

这是我得到的错误:{

"errorMessage": "list indices must be integers or slices, not str",
  "errorType": "TypeError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      35,
      "lambda_handler",
      "print(['AttachedPolicies']['PolicyName'])"
    ]

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为"AttachedPolicies"的值实际上是字典列表。否则,您甚至无法在内部拥有多个相同名称的键。

尝试以下方法:

for d in attached_policy_dict["AttachedPolicies"]:
    print(d["PolicyName"])