ANOL GHOSH
ANOL GHOSH

Reputation: 1

Remove empty dictionary(nested) from list Python

data = [
    {
        "2022": [
            {
                "Title": "Title"
            },
            {
                "Title": "Title 2"
            }
        ]
    },
    {
        "2023": []
    },
    {
        "2024": []
    }
]

Now I want to remove 2023 and 2024 because it do not have any value. Solution in python :

for el in data:
    for dict in el.values():
        if len(dict) == 0:
            data.remove(el)

Similar Solution in JS :

data = data.filter(item=>Object.values(item)[0].length > 0)

What i want is similar to js. (I am not an expert in python)

Upvotes: 0

Views: 49

Answers (2)

Shahab Rahnama
Shahab Rahnama

Reputation: 1012

A better way:

data = [ item  for item in data if list(item.values())[0] ]

Output:

[{'2022': [{'Title': 'Title'}, {'Title': 'Title 2'}]}]

Or:

data = [ item  for item in data for key in item.keys() if item[key] != [] ]

Output:

[{'2022': [{'Title': 'Title'}, {'Title': 'Title 2'}]}]

Upvotes: 1

hide1nbush
hide1nbush

Reputation: 935

Solution in one line:

data = [
    {
        "2022": [
            {
                "Title": "Title"
            },
            {
                "Title": "Title 2"
            }
        ]
    },
    {
        "2023": []
    },
    {
        "2024": []
    }
]

# using list comprehension
result = [{k: v} for el in data for k, v in el.items() if len(v) > 0]
print(f"list comprehension way: {result}")
# or you are a fan of Functional programming
data = filter(lambda x: len(list(x.values())[0]) > 0, data)
# note that filter function returns a filter object, a.k.a. iterator,
# which cannot be accessed by using `plain print` but using `for loop`
for i in data:
    print(i)
print(data)

Output:

list comprehension way: [{'2022': [{'Title': 'Title'}, {'Title': 'Title 2'}]}]
{'2022': [{'Title': 'Title'}, {'Title': 'Title 2'}]}
<filter object at 0x103804050>

Upvotes: 2

Related Questions