Remove an item from a dictionary when its key is unknown

前端 未结 10 1274
悲哀的现实
悲哀的现实 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 19:48

    The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'

    Example:

    >>> dic = {'a':1, 'b':2}
    >>> dic
    {'a': 1, 'b': 2}
    >>> dic.pop('c', 0)
    0
    >>> dic.pop('a', 0)
    1
    >>> dic
    {'b': 2}
    

提交回复
热议问题