Filter dict to contain only certain keys?

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

    Here's an example in python 2.6:

    >>> a = {1:1, 2:2, 3:3}
    >>> dict((key,value) for key, value in a.iteritems() if key == 1)
    {1: 1}
    

    The filtering part is the if statement.

    This method is slower than delnan's answer if you only want to select a few of very many keys.

提交回复
热议问题