0
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)

7
  • What's the point of having 1 element dictionaries? Commented Sep 8, 2022 at 7:22
  • 4
    data = [item for item in data if next(iter(item.values()))] Commented Sep 8, 2022 at 7:22
  • @matszwecja its just a reference. in real data coming from json file. Commented Sep 8, 2022 at 7:24
  • I mean the outer ones contained in data. Will they ever contain anything else than a single year key? Commented Sep 8, 2022 at 7:27
  • @matszwecja we are using list.append() to connate multiple json file. there are more process goes on till we reach this point. here JSON object are not manual driven. Commented Sep 8, 2022 at 7:31

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

data = list(filter(lambda x: len(list(x.values())[0]) > 0, data)) This will remove filter object
@ANOLGHOSH Yes. But using iterator will have better performance if you intend to use it in for loop.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.