Home > Enterprise >  How to delete some python data?
How to delete some python data?

Time:07-20

Good afternoon, gentlemen, help solve this problem. You need to delete where there are empty " and where in the data there is " and write a dictionary to a new list.

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, don't hit hard :0

CodePudding user response:

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