Remove an item from a dictionary when its key is unknown

前端 未结 10 1229
悲哀的现实
悲哀的现实 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:56
    a = {'name': 'your_name','class': 4}
    if 'name' in a: del a['name']
    
    0 讨论(0)
  • 2020-11-29 20:00

    I'd build a list of keys that need removing, then remove them. It's simple, efficient and avoids any problem about simultaneously iterating over and mutating the dict.

    keys_to_remove = [key for key, value in some_dict.iteritems()
                      if value == value_to_remove]
    for key in keys_to_remove:
        del some_dict[key]
    
    0 讨论(0)
  • 2020-11-29 20:02

    items() returns a list, and it is that list you are iterating, so mutating the dict in the loop doesn't matter here. If you were using iteritems() instead, mutating the dict in the loop would be problematic, and likewise for viewitems() in Python 2.7.

    I can't think of a better way to remove items from a dict by value.

    0 讨论(0)
  • 2020-11-29 20:02
    y={'username':'admin','machine':['a','b','c']}
    if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]
    
    0 讨论(0)
提交回复
热议问题