AttributeError: 'unicode' object has no attribute 'pop' - Python list of dictionaries

AttributeError: 'unicode' object has no attribute 'pop' - Python list of dictionaries

我有

    my_dict = {
          "test_environments": [
            {
              "Branch Coverage": "97/97(100%)",
              "project" : 'ok'
            },
            {
              "Branch Coverage": "36/36(100%)",
              "project" :'ok'
            }
          ]
        }

如何删除关键的 Branch Coverage?我正在尝试使用此代码:

   for index, _ in enumerate(my_dict['test_environments']):
        for key, values in my_dict['test_environments'][index].items():
            key.pop("Branch Coverage")

您可以使用 del 关键字从字典中删除关键字 in-place。

my_dict = {
          "test_environments": [
                {
                  "Branch Coverage": "97/97(100%)",
                  "project" : 'ok'
                },
                {
                  "Branch Coverage": "36/36(100%)",
                  "project" :'ok'
                }
        ]
    }

for element in my_dict["test_environments"]:
    del element["Branch Coverage"]

# Prints {'test_environments': [{'project': 'ok'}, {'project': 'ok'}]}
print(my_dict)

您在要修改的 dict 对象上调用 pop,而不是要删除的键。

for d in my_dict['test_environments']:
    d.pop("Branch Coverage")