Home > database >  Removing a key in a list of dictionary with if value condition in python
Removing a key in a list of dictionary with if value condition in python

Time:07-19

Here's my sample data, I want to remove the keys with "N/A" values using python.

Data = [
  {
    "Area": "Los Angeles",
    "Idle": "N/A",
    "Downtime": "N/A",
    "Production": "N/A",
    "Total": "0.00 kWh",
    "Total_Cost": "$ 0.00",
    "Total_Idle_Cost": "N/A"
  },
  {
    "Area": "Oklohoma",
    "Idle": "N/A",
    "Downtime": "N/A",
    "Production": "N/A",
    "Total": "0.00 kWh",
    "Total_Cost": "$ 0.00",
    "Total_Idle_Cost": "N/A"
  }]

The output i want, remove the keys with "N/A" value.

 Data = [
      {
        "Area": "Los Angeles",
        "Total": "0.00 kWh",
        "Total_Cost": "$ 0.00",
      },
      {
        "Area": "Oklohoma",
        "Total": "0.00 kWh",
        "Total_Cost": "$ 0.00",
      }]

CodePudding user response:

you can try:

Data = [{key: value for key, value in entry.items() if value != "N/A"} for entry in Data]

CodePudding user response:

Try this:

def returnNewDict(oldDict):
    newDict = {}
    for key, value in oldDict.items():
        if value != 'N/A':
            newDict[key] = value
    return newDict

newData = [returnNewDict(oldDict) for oldDict in Data]
  • Related