Home > Net >  Remove empty dictionary(nested) from list Python
Remove empty dictionary(nested) from list Python

Time:09-08

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)

CodePudding user response:

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>

CodePudding user response:

You can use this:

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

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

Output:

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