【问题标题】:not being able to get a value from a dictionary无法从字典中获取值
【发布时间】:2019-03-07 22:44:42
【问题描述】:

我正在尝试遍历字典并获取键“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'])"
    ]

【问题讨论】:

    标签: python dictionary lambda


    【解决方案1】:

    这是因为"AttachedPolicies" 的值实际上是一个字典列表。否则你甚至不能在里面有几个同名的键。

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2021-07-01
      • 2016-05-09
      • 1970-01-01
      • 2022-12-17
      • 2019-06-18
      相关资源
      最近更新 更多