Home > Mobile >  Python dictionary - Remove dictionary from list of dictionaries
Python dictionary - Remove dictionary from list of dictionaries

Time:03-10

I have this dictionary:

 my_dict = {
  "camel_configuration": "rEIP.cccf",
  "test_environments": [
    {
      "Branch Coverage": "78/78(100%)",
      "Test Environment": "AB",
      "Statement Coverage": "73/73(100%)",
      "Test Status": "25",
      "MC/DC Coverage": "17/17(100%)"
    },
    {
      "Branch Coverage": "-",
      "Test Environment": "None",
      "Statement Coverage": "-",
      "Test Status": "36/36(100%)",
      "MC/DC Coverage": "-"
    }
  ]
}

How to remove a dictionary whose value of Test Environment is None? How to modify it so that I get this:

 my_dict = {
  "camel_configuration": "rEIP.cccf",
  "test_environments": [
    {
      "Branch Coverage": "78/78(100%)",
      "Test Environment": "AB",
      "Statement Coverage": "73/73(100%)",
      "Test Status": "25",
      "MC/DC Coverage": "17/17(100%)"
    }
]
}

CodePudding user response:

my_dict = {
    "camel_configuration": "rEIP.cccf",
    "test_environments": [
        {
            "Branch Coverage": "78/78(100%)",
            "Test Environment": "AB",
            "Statement Coverage": "73/73(100%)",
            "Test Status": "25",
            "MC/DC Coverage": "17/17(100%)",
        },
        {
            "Branch Coverage": "-",
            "Test Environment": "None",
            "Statement Coverage": "-",
            "Test Status": "36/36(100%)",
            "MC/DC Coverage": "-",
        },
    ],
}
my_dict["test_environments"] = [
    test_environment
    for test_environment in my_dict["test_environments"]
    if test_environment["Test Environment"] != "None"
]
import pprint as pp

pp.pprint(my_dict, indent=2)
  • Related