2014-07-11 108 views
0

请原谅我,如果它看起来是重复的。我已经使用了link 1link 2删除键字典python

提供的方法我使用的是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 

另外,我请你帮助我了解如何答复的答复。每次我都无法正确回复。换行符或编写代码不适用于我。谢谢。

+0

你是什么意思*“了解如何回复答复”*?如果您对SO本身有疑问,请考虑http://meta.stackoverflow.com – jonrsharpe

+2

是的,您无法撰写多行注释。编辑您的问题以添加重要信息,包括代码。但是你可以使用反引号来“内联等宽片段”。 –

+0

@jonrsharpe嗨,我无法得到正确的缩进,在我的答复中断行。我可以正确地发布问题,但在回复评论方面有困难。 :( –

回答

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 
+0

谢谢,这完全符合我的想法。 –