How to delete some python data?

Question:

I need to delete where there are empty " and where in the data there is " and write a dictionary to a new list.

Data structure:

list_1 = [
       {
          "Client": [
             ""
          ],
          "description": ""
       },
       {
          "Client": [
             ""
          ],
          "description": ""
       },{
          "Client": [
             "Any value",
             "",
             "Any value",
             ""
          ],
          "description": "Any value"
       },
       {
          "Client": [
             "",
             "",
             "",
             "Any value"
          ],
          "description": "Any value"
       }]


result =  [{
          "Client": [
             "Any value",
             "Any value"
          ],
          "description": "Any value"
       },
       {
          "Client": [
             "Any value"
          ],
          "description": "Any value"
       },
       {
          "Client": [
             "Any value"
          ],
          "description": "Any value"
       },
       {
          "Client": [
             "Any value"
          ],
          "description": "Any value"
       }]

I tried it and it didn’t work out:

result = []
for res in list_1:
    if res['Client'] not in '':
        result.append(res)

I don’t know much about the data structure.

Asked By: Alexey

||

Answers:

Sure:

result = []
for obj in list_1:
    # "Compact" the client list by removing all falsy values
    compacted_clients = [c for c in obj["Client"] if c]
    if compacted_clients:  # If any remain, this is a valid object
        # ... so append a copy with the compacted client list
        result.append({**obj, "Client": compacted_clients})
print(result)

This prints out

[{'Client': ['Any value', 'Any value'], 'description': 'Any value'}, {'Client': ['Any value'], 'description': 'Any value'}]
Answered By: AKX
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.