首页 > 解决方案 > 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'

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

标签: pythonjsonpython-3.xlistdictionary

解决方案


您可以使用列表推导替换整个列表,保留其他项目:

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整个列表的循环进度


推荐阅读