Filter dict to contain only certain keys?

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

    This function will do the trick:

    def include_keys(dictionary, keys):
        """Filters a dict by only including certain keys."""
        key_set = set(keys) & set(dictionary.keys())
        return {key: dictionary[key] for key in key_set}
    

    Just like delnan's version, this one uses dictionary comprehension and has stable performance for large dictionaries (dependent only on the number of keys you permit, and not the total number of keys in the dictionary).

    And just like MyGGan's version, this one allows your list of keys to include keys that may not exist in the dictionary.

    And as a bonus, here's the inverse, where you can create a dictionary by excluding certain keys in the original:

    def exclude_keys(dictionary, keys):
        """Filters a dict by excluding certain keys."""
        key_set = set(dictionary.keys()) - set(keys)
        return {key: dictionary[key] for key in key_set}
    

    Note that unlike delnan's version, the operation is not done in place, so the performance is related to the number of keys in the dictionary. However, the advantage of this is that the function will not modify the dictionary provided.

    Edit: Added a separate function for excluding certain keys from a dict.

    0 讨论(0)
  • 2020-11-22 11:27

    You could use python-benedict, it's a dict subclass.

    Installation: pip install python-benedict

    from benedict import benedict
    
    dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])
    

    It's open-source on GitHub: https://github.com/fabiocaccamo/python-benedict


    Disclaimer: I'm the author of this library.

    0 讨论(0)
  • 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}
    >>> 
    
    0 讨论(0)
  • 2020-11-22 11:30

    You can do that with project function from my funcy library:

    from funcy import project
    small_dict = project(big_dict, keys)
    

    Also take a look at select_keys.

    0 讨论(0)
  • 2020-11-22 11:32

    Slightly more elegant dict comprehension:

    foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题