Remove all elements of a string list in python if they contain a given phrase

Tags: , , , ,



Have a list called summary containing a corresponding JSON object similar to:

{
   # summary[0]
   "object1": {
      "json_data": "{json data information}",
      "tables_data": "TABLES_DATA"
   },

   # summary[1]
   "object2": {
      "json_data": "{json data information}",
      "tables_data": ""
   }
}

Essentially, if "tables_data": "" is found within the string of a list item, I want the entire list item to be removed.

How would I go about doing this?

Answer

You can do a dictionary-comprehension selecting the dictionary item with 'tables_data' has a value not equals '':

summary = [{
   # summary[0]
   "object1": {
      "json_data": "{json data information}",
      "tables_data": "TABLES_DATA"
   },

   # summary[1]
   "object2": {
      "json_data": "{json data information}",
      "tables_data": ""
   }
}]
result = [{k: d for k, d in s.items() if d.get('tables_data') != ''} for s in summary]
# [{'object1': {'json_data': '{json data information}', 'tables_data': 'TABLES_DATA'}}]


Source: stackoverflow