Death Metal
Death Metal

Reputation: 892

remove Key in dictionary python

Please pardon me if it looks to be a duplicate. I have used the methods as provided at link 1 and link 2

Python version I am using 2.7.3. I am passing a dictionary into a function and Want to remove keys if a condition is true.

When I check the length before and after passing dictionary are same.

My code is:

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

Also, I request you to help me understand how to reply to the replies. Every time I fail to reply properly. The line breaks or writing code doesn't work with me. Thank you.

Upvotes: 1

Views: 272

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121945

This happens because the dictionary is unpacked and repacked into the keyword parameter **dictArgum, so the dictionary you see inside the function is a different object:

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


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

Instead, pass the dictionary directly:

def checkDomain(dictArgum): # no asterisks here

    ...

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

checkDomain(predictDict) # or here

or return and assign it:

def checkDomain(**dictArgum):

    ...

    return dictArgum # return modified dict

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

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

Upvotes: 3

Related Questions