Python3删除整个嵌套字典

2024-10-04 01:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

{'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'

所以我不知道现在该怎么办:-(


Tags: nameinnoneidresultlevelcompanystate
1条回答
网友
1楼 · 发布于 2024-10-04 01:35:47

您可以使用列表理解来替换整个列表,保留其他项:

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]),但不能在循环中执行此操作,因为它有consequences for the ^{} loop progress across the list

相关问题 更多 >