Skip to content
Advertisement

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

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?

Advertisement

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement