Home > Enterprise >  remove {} from OrderedDict
remove {} from OrderedDict

Time:09-21

My method to create data using taskIdSerializer given in below:

def to_representation(self, instance):
        result = super(taskIdSerializer, self).to_representation(instance)
        result = OrderedDict([(key, result[key]) for key in result if result['date']])
        return result

This result return in my function given in below:

[
    {
        "description": "asdsa",
        "priority_id": 3,
        "name": "tetst",
        "date": [
            {
                "dates": "20/09/2021 15:14:00",
                "id": 146
            },
            {
                "dates": "20/09/2021 15:14:00",
                "id": 145
            }
        ]
    },
    {}, // this is value add dict when date = []
    {}  // this is value add dict when date = []
]

I want remove {} object and ı want to get return data like this:

[
        {
            "description": "asdsa",
            "priority_id": 3,
            "name": "tetst",
            "date": [
                {
                    "dates": "20/09/2021 15:14:00",
                    "id": 146
                },
                {
                    "dates": "20/09/2021 15:14:00",
                    "id": 145
                }
            ]
        }
    ]

CodePudding user response:

What you have doesn't look like an OrderedDict to me. An OD is usually represented as a list of tuple pairs. You are showing a list of dictionaries.

If your list is always going to be two elements long, then you can just say

result.pop()

which removes the last element from the list.

You could make it a little tighter by saying:

if result[-1] == {}:
    result.pop()

But, in general, I think you need to go back and have a deeper understanding of what output you are generating.

Happy coding! :)

CodePudding user response:

Use the pop() function to remove.

  • Related