>> json.dumps(event, indent=4) "even-6ren">
gpt4 book ai didi

python - 如果 Python 中的值为空、 "null"或 None,则删除字典列表中的项目

转载 作者:行者123 更新时间:2023-11-30 23:00:59 25 4
gpt4 key购买 nike

我有一个 JSON 对象,其中包含各种不必要的值,例如 "null"""None.如果整个对象包含这样的值,我想删除它。

>>> json.dumps(event, indent=4)
"event" = {
"status": "COMPLETED",
"dataValues": [
{
"key": "wiiDcsQ5pdQ",
"value": "25"
},
{
"key": "RsZ4gQzWPWU",
"value": "null"
},
{
"key": "L7aO70bcrbP",
"value": ""
},
{
"key": "gY6pXRwdThm",
"value": "null"
},
{
"key": "x1708y0C4C7",
"value": False
}
]
}

我失败的尝试:

no_values = ["null", "", None]

# no changes/deletions:
[elem for elem in event['dataValues'] if elem['value'] not in no_values]

# TypeError: argument of type 'bool' is not iterable
[elem for elem in event['dataValues'] if any(s in elem['value'] for s in no_values]

我该怎么做?

最佳答案

这对我有用,我将数据存储在变量中并使用您的第一个列表理解对其进行评估。请注意,我使用了一组被忽略的值,这稍微快一些:

In [12]: import json

In [13]: json_text = """{
"status": "COMPLETED",
"dataValues": [
{
"key": "wiiDcsQ5pdQ",
"value": "25"
},
{
"key": "RsZ4gQzWPWU",
"value": "null"
},
{
"key": "L7aO70bcrbP",
"value": ""
},
{
"key": "gY6pXRwdThm",
"value": null
},
{
"key": "x1708y0C4C7",
"value": false
}
]
}"""

In [14]: data = json.loads(json_text)

In [15]: ignored_values = set(["null", "", None])

In [16]: [elem for elem in data['dataValues'] if elem['value'] not in ignored_values]
Out[16]:
[{u'key': u'wiiDcsQ5pdQ', u'value': u'25'},
{u'key': u'x1708y0C4C7', u'value': False}]

关于python - 如果 Python 中的值为空、 "null"或 None,则删除字典列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35064561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com