在python中使用if value条件从字典列表中删除一个键



这是我的样本数据,我想删除带有"N/A">

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"
}]

我想要的输出,删除带有"N/A"价值。

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

你可以试试:

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

试试这个:

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]
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"
}]     
def NAremove1(d):
if not isinstance(d,dict):
return d if not isinstance(d,list) else list(map(NAremove1,d))
return { k:NAremove1(v) for k,v in d.items() if v != 'N/A'}
print(NAremove1(Data)) 

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

相关内容

  • 没有找到相关文章

最新更新