1

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.

Community
  • 1
  • 1
Death Metal
  • 830
  • 3
  • 9
  • 26
  • What do you mean by *"understand how to reply to the replies"*? If you have a question about SO itself, consider http://meta.stackoverflow.com – jonrsharpe Jul 11 '14 at 17:09
  • 2
    Yeah, you can't write multi-line comments. Edit your question to add significant information, including code. But you can use backticks for `inline monospace snippets`. – Lev Levitsky Jul 11 '14 at 17:12
  • @jonrsharpe Hi, I cannot get proper indentation, line breaks in my replies. I can post the questions properly, but have tough time in replying to comments.! :( – Death Metal Jul 11 '14 at 17:12
  • @LevLevitsky is right - comments are not the correct place to put code. – jonrsharpe Jul 11 '14 at 17:13
  • @LevLevitsky - Code edited. Sorry. – Death Metal Jul 11 '14 at 17:16
  • I was not referring to the code in your question. I was answering your question about replying to answers. "Replies to replies" are called "comments on answers" in Stack Overflow terminology. – Lev Levitsky Jul 11 '14 at 17:18

1 Answers1

3

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437