如果在 Python 中找到空列表,则删除字典

Remove a dictinoary if empty list is found in Python

我有一份词典列表。以下是我的示例数据:

[
  {
    "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": []
  }
]

如果我发现事务列表是empty.Below这里我需要删除字典empty.Below是我试过的代码:

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

请告诉我该怎么做。提前致谢!

你可以使用下面的列表理解

res = [sub for sub in results if sub['Transaction']]

结果

[
    {
       'Customer_id': '123', 
       'Amount': 3000, 
       'Account_no': 
       '123456789012', 
       'Transaction': 
           [
               {
                   'Comments': 'Valuable items', 
                   'time': '12:19:39', 
                   'date': '20/06/25', 
                   'Shop': 'Amazon'
               }
          ]
     }
]

  • 不清楚数据的最终目标是什么,但如果您还想进行任何分析,使用 pandas 是一种选择。
  • 具体来说,使用 pandas.json_normalize,这对于读取 JSON (dict) 数据列表非常有用
    • Transaction为空列表时,该组数据在解析时将被忽略
  • 给出以下示例,使用您的示例 JSON 分配给 data
  • 注意数据帧不包含数据,其中 Transaction 为空
  • 现在可以分析数据了。
  • 根据示例数据,此答案假定 Transaction 键将始终存在。
import pandas as pd

# create the dataframe
df = pd.json_normalize(data, 'Transaction', ['Customer_id', 'Account_no', 'Amount'])

# display(df)
       date      time    Shop        Comments Customer_id    Account_no Amount
0  20/06/25  12:19:39  Amazon  Valuable items         123  123456789012   3000