【发布时间】:2020-11-01 14:42:13
【问题描述】:
我有一个字典列表。以下是我的示例数据:
[
{
"Customer_id": "123",
"Account_no": "123456789012",
"Amount": 3000,
"Transaction": [
{
"date": "20/06/25",
"time": "12:19:39",
"Shop": "Amazon",
"Comments": "Valuable items"
}
]
},
{
"Customer_id": "123",
"Account_no": "123456789012",
"Amount": 3000,
"Transaction": []
}
]
如果我发现事务列表为空,我需要删除字典。下面是我尝试的代码:
res=list(filter(None,({key:val for key,val in sub.items() if val} for sub in results)))
#results is the list of dictionary
我的输出:
[
{
"Customer_id": "123",
"Account_no": "123456789012",
"Amount": 3000,
"Transaction": [
{
"date": "20/06/25",
"time": "12:19:39",
"Shop": "Amazon",
"Comments": "Valuable items"
}
]
},
{
"Customer_id": "123",
"Account_no": "123456789012",
"Amount": 3000,
}
]
我只能删除该特定列表,而不能删除与之相关的详细信息。
预期输出:
[
{
"Customer_id": "123",
"Account_no": "123456789012",
"Amount": 3000,
"Transaction": [
{
"date": "20/06/25",
"time": "12:19:39",
"Shop": "Amazon",
"Comments": "Valuable items"
}
]
}
]
请告诉我该怎么做。提前致谢!
【问题讨论】:
-
使用列表理解,
[v for v in results if v.get('Transaction')]
标签: python json-normalize