Filter dict to contain only certain keys?

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

    Another option:

    content = dict(k1='foo', k2='nope', k3='bar')
    selection = ['k1', 'k3']
    filtered = filter(lambda i: i[0] in selection, content.items())
    

    But you get a list (Python 2) or an iterator (Python 3) returned by filter(), not a dict.

提交回复
热议问题