Filter dict to contain only certain keys?

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

    If we want to make a new dictionary with selected keys removed, we can make use of dictionary comprehension
    For example:

    d = {
    'a' : 1,
    'b' : 2,
    'c' : 3
    }
    x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
    y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
    # x is {'a': 1, 'b': 2}
    # y is {'a': 1, 'b': 2}
    

提交回复
热议问题