python - Python3删除整个嵌套字典
问题描述
{'result':{'result':[
{
'Company':{
'PostAddress':None
},
'ExternalPartnerProperties':None,
'Id':123456,
'Level':'Level1',
'Name':'Name1',
'ParentId':456789,
'State':'InTrial',
'TrialExpirationTime':1435431669
},
{
'Company':{
'PostAddress':None
},
'ExternalPartnerProperties':None,
'Id':575155,
'Level':'Level2',
'Name':'Name2',
'ParentId':456789,
'State':'InTrial',
'TrialExpirationTime':1491590226
},
{
'Company':{
'PostAddress':None
},
'ExternalPartnerProperties':None,
'Id':888888,
'Level':'Level2',
'Name':'Name3',
'ParentId':456789,
'State':'InProduction',
'TrialExpirationTime':1493280310
},
我的代码:
for i in partner_output['result']['result']:
if "InProduction" in i['State']:
del i['Company'], i['ExternalPartnerProperties'], i['Id'], i['Level'], i['Name'], i['ParentId'], i['State'], i['TrialExpirationTime']
如果我这样做,那么我返回以下结果
{'result': {'result': [{
'Company':{
'PostAddress':None
},
'ExternalPartnerProperties':None,
'Id':123456,
'Level':'Level1',
'Name':'Name1',
'ParentId':456789,
'State':'InTrial',
'TrialExpirationTime':1435431669
},
{
'Company':{
'PostAddress':None
},
'ExternalPartnerProperties':None,
'Id':575155,
'Level':'Level2',
'Name':'Name2',
'ParentId':456789,
'State':'InTrial',
'TrialExpirationTime':1491590226
},
{},
但项目总数仍然是 3 ...第三个容器只是空的,但仍然是一个容器。如何一起删除第三个容器?
我不能使用:
for i in partner_output['result']['result']:
if "InProduction" in i['State']:
del partner_output['result'][i]
因为我收到错误:
TypeError: unhashable type: 'dict'
所以我现在不知道该怎么办:-(
解决方案
您可以使用列表推导替换整个列表,保留其他项目:
partner_output['result']['result'] = [
i for i in partner_output['result']['result']
if i['State'] != "InProduction"
]
请注意,过滤器的测试已颠倒过来;您想保留所有未'State'
设置为 的项目InProduction
。或者,保留状态设置为的值InTrial
:
partner_output['result']['result'] = [
i for i in partner_output['result']['result']
if i['State'] == "InTrial"
]
您的第二次尝试失败了,因为您尝试使用i
对字典的引用作为外部 partner_output['result']
字典中的键。如果您想从partner_output['result']['result']
列表中删除某些内容,则必须使用整数索引 ( del partner_output['result']['result'][2]
),但您不能在循环中执行此操作,因为这会影响for
整个列表的循环进度。
推荐阅读
- python - 如何在 OpenCV 中的点之间画线?
- python - 使用 Python turtle 时如何按顺序选择颜色?
- r - 在带有 rpy2 的 jupyter 笔记本中找不到 ggplot 函数
- php - 检索最后更新的 id
- r - 从 R Shiny 中的数据中删除空白级别
- scikit-learn - 使用更多的 n-gram 顺序如何降低多项 NaiveBayes 分类器的准确性?
- socket.io - socket.io : socket IO 客户端是否可以发出函数注册回调函数
- javascript - Trie 实现中出现错误(Javascript)
- javascript - 从 Cloud Firestore 在 MatDatepicker 中加载时间戳 | 火力基地
- sql - 选择实际身高