删除字典python中的键

2024-09-29 21:50:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如果它看起来像是复制品,请原谅。我使用了link 1和{a2}中提供的方法

我使用的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

同时,我请求你帮助我理解如何答复答复答复。每次我回答不好的时候。行中断或编写代码对我不起作用。非常感谢。在


Tags: orthekey代码字典keysoutthis
1条回答
网友
1楼 · 发布于 2024-09-29 21:50:45

这是因为字典被解包并重新打包到关键字参数**dictArgum,因此您在函数中看到的字典是一个不同的对象:

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


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

相反,直接传递字典:

^{pr2}$

或者return并分配它:

def checkDomain(**dictArgum):

    ...

    return dictArgum # return modified dict

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

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

相关问题 更多 >

    热门问题