【问题标题】:remove Key in dictionary python删除字典python中的键
【发布时间】:2014-09-02 09:23:20
【问题描述】:

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

我使用的是 2.7.3 的 Python 版本。我将字典传递给函数,如果条件为真,我想删除键。

当我检查通过字典前后的长度是否相同。

我的代码是:

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

另外,我请求您帮助我了解如何回复这些回复。每次我都无法正确回复。换行或编写代码对我不起作用。谢谢。

【问题讨论】:

  • “了解如何回复回复”是什么意思?如果您对 SO 本身有疑问,请考虑 meta.stackoverflow.com
  • 是的,你不能写多行 cmets。编辑您的问题以添加重要信息,包括代码。但是您可以对inline monospace snippets 使用反引号。
  • @jonrsharpe 嗨,我的回复无法正确缩进,换行。我可以正确发布问题,但很难回复 cmets.! :(
  • @LevLevitsky 是对的 - cmets 不是放置代码的正确位置。
  • @LevLevitsky - 代码已编辑。对不起。

标签: python python-2.7 dictionary


【解决方案1】:

发生这种情况是因为字典被解包并重新打包到关键字参数**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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2014-01-08
    • 1970-01-01
    • 2012-07-01
    相关资源
    最近更新 更多