Remove an item from a dictionary when its key is unknown

前端 未结 10 1276
悲哀的现实
悲哀的现实 2020-11-29 19:12

What is the best way to remove an item from a dictionary by value, i.e. when the item\'s key is unknown? Here\'s a simple approach:

for key, item in some_di         


        
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 19:41

    Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as

    some_dict = {key: value for key, value in some_dict.items() 
                 if value is not value_to_remove}
    

    But this may not do what you want:

    >>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
    >>> value_to_remove = "You say yes"
    >>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
    >>> some_dict
    {1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
    >>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
    >>> some_dict
    {1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
    

    So you probably want != instead of is not.

提交回复
热议问题