Filter dict to contain only certain keys?

后端 未结 15 1104
耶瑟儿~
耶瑟儿~ 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.

提交回复
热议问题