Remove an item from a dictionary when its key is unknown

前端 未结 10 1252
悲哀的现实
悲哀的现实 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:52

    c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a

    c = {key:a[key] for key in a.keys() - {'z', 'w'}}
    

    Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html

提交回复
热议问题