Filter dict to contain only certain keys?

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

    We can do simply with lambda function like this:

    >>> dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
    >>> large_dict = {"a":1,"b":2,"c":3,"d":4}
    >>> new_dict_keys = ("c","d")
    >>> small_dict=dict_filter(large_dict, new_dict_keys)
    >>> print(small_dict)
    {'c': 3, 'd': 4}
    >>> 
    

提交回复
热议问题