Home > Enterprise >  AttributeError: 'unicode' object has no attribute 'pop' - Python list of diction
AttributeError: 'unicode' object has no attribute 'pop' - Python list of diction

Time:03-02

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")

CodePudding user response:

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)

CodePudding user response:

You call pop on the dict object you want to modify, not the key you want to remove.

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