提问者:小点点

dictionary python中的删除键


def checkDomain(**dictArgum):

    for key in dictArgum.keys():

         inn=0
         out=0
         hel=0
         pred=dictArgum[key]

         #iterate over the value i.e pred.. increase inn, out and hel values

         if inn!=3 or out!=3 or hel!=6:
                   dictArgum.pop(key, None)# this tried
                   del dictArgum[key] ###This also doesn't remove the keys 

print "The old length is ", len(predictDict) #it prints 86

checkDomain(**predictDict) #pass my dictionary

print "Now the length is ", len(predictDict) #this also prints 86

另外,我请求你帮助我理解如何回复这些回复。每次我都没能恰当地回复。换行或编写代码对我来说不起作用。谢谢你。


共1个答案

匿名用户

发生这种情况是因为字典被解压缩并重新打包到关键字参数**dictargum中,因此您在函数中看到的字典是一个不同的对象:

>>> def demo(**kwargs):
    print id(kwargs)


>>> d = {"foo": "bar"}
>>> id(d)
50940928
>>> demo(**d)
50939920 # different id, different object

而是直接传递字典:

def checkDomain(dictArgum): # no asterisks here

    ...

print "The old length is ", len(predictDict)

checkDomain(predictDict) # or here

返回并分配:

def checkDomain(**dictArgum):

    ...

    return dictArgum # return modified dict

print "The old length is ", len(predictDict)

predictDict = checkDomain(**predictDict) # assign to old name