从Python列表中删除空字典(嵌套)


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

现在我想删除2023年和2024年,因为它没有任何价值。python中的解决方案:

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

JS中的类似解决方案:

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

我想要的类似于js。(我不是python专家(

一行解决方案:

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)

输出:

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

更好的方法:

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

输出:

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

或者:

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

输出:

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

相关内容

  • 没有找到相关文章

最新更新