删除字典python中的键

时间:2014-07-11 17:07:27

标签: python python-2.7 dictionary

请原谅我,如果它看起来是重复的。我使用了link 1link 2

中提供的方法

Python版我使用的是2.7.3。我正在将字典传递给函数,并且如果条件为真,则要删除密钥。

当我检查传递字典之前和之后的长度是相同的。

我的代码是:

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 个答案:

答案 0 :(得分:3)

这是因为字典被解压缩并重新打包到关键字参数**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

return并指定它:

def checkDomain(**dictArgum):

    ...

    return dictArgum # return modified dict

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

predictDict = checkDomain(**predictDict) # assign to old name
相关问题