Slicing a dictionary

后端 未结 6 916
后悔当初
后悔当初 2020-12-02 10:28

I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:

# the dictionary
d = {1:         


        
6条回答
  •  庸人自扰
    2020-12-02 11:07

    Write a dict subclass that accepts a list of keys as an "item" and returns a "slice" of the dictionary:

    class SliceableDict(dict):
        default = None
        def __getitem__(self, key):
            if isinstance(key, list):   # use one return statement below
                # uses default value if a key does not exist
                return {k: self.get(k, self.default) for k in key}
                # raises KeyError if a key does not exist
                return {k: self[k] for k in key}
                # omits key if it does not exist
                return {k: self[k] for k in key if k in self}
            return dict.get(self, key)
    

    Usage:

    d = SliceableDict({1:2, 3:4, 5:6, 7:8})
    d[[1, 5]]   # {1: 2, 5: 6}
    

    Or if you want to use a separate method for this type of access, you can use * to accept any number of arguments:

    class SliceableDict(dict):
        def slice(self, *keys):
            return {k: self[k] for k in keys}
            # or one of the others from the first example
    
    d = SliceableDict({1:2, 3:4, 5:6, 7:8})
    d.slice(1, 5)     # {1: 2, 5: 6}
    keys = 1, 5
    d.slice(*keys)    # same
    

提交回复
热议问题