Filter dict to contain only certain keys?

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

    Given your original dictionary orig and the set of entries that you're interested in keys:

    filtered = dict(zip(keys, [orig[k] for k in keys]))
    

    which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of keys existing in your original dictionary.

提交回复
热议问题