I am trying to delete items, based upon a lookup table i iterate through inside my python dictionary, but am not able to delete the values. This post depends on python 3.8 to work with.
inEvent = {
"event_data": {
"event_name": "Test",
"station_id": "Station1",
"serial_no": "1234",
},
"tests": [
{
"name": "Temperature from Sensor 1",
"status": "Passed",
"value": "21.0",
"limits": [],
"units": "°C",
},
{
"name": "Power Measurement CH1",
"status": "Passed",
"value": "30.9",
"limits": [],
"units": "W",
},
{
"name": "Slope Check: Measured Slope CH1",
"status": "Passed",
"value": "1234.5678",
"limits": {"low": "0", "high": None},
"units": [],
},
{
"name": "Slope Check: Measured Slope CH2",
"status": "Passed",
"value": "-1",
"limits": [],
"units": [],
},
],
"plots": [],
}
while iterating over my dictionary i replace matching names, but in rare cases i want to delete the complete matching test entry. for e.g.{"name": "Slope Check: Measured Slope CH1", "status":"Passed","value": "1234.5678","limits": {"low": "0", "high": None},"units": [],}
should be deleted
for t in list(inEvent['tests']):
eventName = t['name']
for row in self.LookUpTable.itertuples(index=False): # own lookuptable excel file
if eventName == row[4] and not pd.isnull(row[5]):
t['name'] = row[5]
break
elif eventName == row[4] and pd.isnull(row[5]):
print(inEvent)
inEvent['tests'].pop(t)
break
CodePudding user response:
I recommend using a nested loop for this. You can do this by looping through all of the keys and values in the dictionary and then loop through all of the keys and values in the nested dictionaries. You can then use an if statement to find the key in teh dictionary that you want to delete. Here is a simple outline of code that you can use (if this does not work then I recommend googling exactly what the issue is and looking further into it):
for key, value in dict.items():
for k, v in k.items():
if v == something:
del key[k]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>