Filter dict to contain only certain keys?

后端 未结 15 941
耶瑟儿~
耶瑟儿~ 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:42

    Short form:

    [s.pop(k) for k in list(s.keys()) if k not in keep]
    

    As most of the answers suggest in order to maintain the conciseness we have to create a duplicate object be it a list or dict. This one creates a throw-away list but deletes the keys in original dict.

提交回复
热议问题