Skip to content
Advertisement

AttributeError: ‘unicode’ object has no attribute ‘pop’ – Python list of dictionaries

I have

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

How could I delete the key Branch Coverage? I’m trying with this code:

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

Advertisement

Answer

You can use the del keyword to remove keys from a dictionary 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)
Advertisement