Filter dict to contain only certain keys?

后端 未结 15 1097
耶瑟儿~
耶瑟儿~ 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条回答
  •  -上瘾入骨i
    2020-11-22 11:45

    This one liner lambda should work:

    dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
    

    Here's an example:

    my_dict = {"a":1,"b":2,"c":3,"d":4}
    wanted_keys = ("c","d")
    
    # run it
    In [10]: dictfilt(my_dict, wanted_keys)
    Out[10]: {'c': 3, 'd': 4}
    

    It's a basic list comprehension iterating over your dict keys (i in x) and outputs a list of tuple (key,value) pairs if the key lives in your desired key list (y). A dict() wraps the whole thing to output as a dict object.

提交回复
热议问题