Filter dict to contain only certain keys?

后端 未结 15 942
耶瑟儿~
耶瑟儿~ 2020-11-22 10:52

I\'ve got a dict that has a whole bunch of entries. I\'m only interested in a select few of them. Is there an easy way to prune all the other ones out?

15条回答
  •  不思量自难忘°
    2020-11-22 11:39

    Here is another simple method using del in one liner:

    for key in e_keys: del your_dict[key]
    

    e_keys is the list of the keys to be excluded. It will update your dict rather than giving you a new one.

    If you want a new output dict, then make a copy of the dict before deleting:

    new_dict = your_dict.copy()           #Making copy of dict
    
    for key in e_keys: del new_dict[key]
    

提交回复
热议问题