简体   繁体   中英

How to remove dictionary from a list if all values of keys are null

Output:

{
        "id": 243,
        "name": "DC KD Postpaid",
        "display_name": "DC KD Postpaid disp.",
        "asigned": [
            {
                "id": null,
                "user": null,
                "email": null,
                "phone": null,
                "fullname": null
            },
            {
                "id": 526,
                "user": "Suraj6",
                "email": "dckd@gmail.com",
                "phone": "9865325285",
                "fullname": "Suraj"
            }
        ]
    }

CentresAssigned Serializer

class CentresAssigned(serializers.ModelSerializer):
    asigned = serializers.SerializerMethodField()

class Meta:
    model = Centers
    fields = ["id", "name", "display_name", "asigned"]

def get_asigned(self, obj):
    if obj.asigned:
        return PanelUserSerializerCopy(obj.asigned, many=True).data
    else:
        return None

PanelUserSerializerCopy

class PanelUserSerializerCopy(serializers.ModelSerializer):
    id = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    email = serializers.SerializerMethodField()
    phone = serializers.SerializerMethodField()
    fullname = serializers.SerializerMethodField()

class Meta:
    model = panel_models.PanelUser
    fields = (
        "id",
        "user",
        "email",
        "phone",
        "fullname"
    )

def get_id(self, obj):
    if obj.user and obj.user.usergroup == 'CCPartner':
        return obj.id
    else:
        return None

def get_user(self, obj):
    if obj.user and obj.user.usergroup == 'CCPartner':
        return obj.user.username
    else:
        return None

def get_email(self, obj):
    if obj.user and obj.user.usergroup == 'CCPartner':
        return obj.user.email
    else:
        return None

def get_phone(self, obj):
    if obj.user and obj.user.usergroup == 'CCPartner':
        return obj.user.phonenumber
    else:
        return None

def get_fullname(self, obj):
    return obj.user.fullname if obj.user and obj.user.usergroup == 'CCPartner' else None

As in the output the first dictionary of all keys contains null value. So i do not want this in the list. How to do this. I am learning Python and DRF and I searched and found items() and del() method but how to apply here. I am having difficulty. Any help would be appreciated. Thank you !!

The simplest way would be to assign the original list to a filtered list:

some_list = [{'a': None, 'b': None}, {'a': 0, 'b': 0}]

filtered_list = filter(lambda d: all(True if i is not None else False for i in d.values()),
                       some_list)

You could also iterate over each dictionary by index and delete the bad values:

for i in range(len(some_list)):
    if all(True if v is not None else False for v in some_list[i].values()):
        del(some_list[i])

Note that in my all checks I am checking if the value is explicitly None . Otherwise you may end up with not-none but Falsey values like "" or [] triggering a filter or delete. If that is not a concern you could simplify the samples I gave even more.

If you want to filter a dictionary based on if all its values are null:

if all(d.values()):
    # keep d
# otherwise throw out

If you want to filter a dictionary based on if any of its values are null:

if any(d.values()):
    # keep d
# otherwise throw out

Also, if you are working with JSON you may want to consider using the built-in json package, which converts JSON to Python objects (including converting Javascript's null to Python's None automatically):

In [1]: import json

In [2]: s = """{"id": null, "user": null, "email": null, "phone": null, "fullname": null}"""

In [3]: json.loads(s)
Out[3]: {'id': None, 'user': None, 'email': None, 'phone': None, 'fullname': None}

Anyway, I loaded your JSON data into a Python dictionary called payload and here's an example:

In [6]: [d for d in payload['asigned'] if all(d.values())]
Out[6]:
[{'id': 526,
  'user': 'Suraj6',
  'email': 'dckd@gmail.com',
  'phone': '9865325285',
  'fullname': 'Suraj'}]

(note that the 'asigned' key is misspelled -- should be 'assigned')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM