pythondictionary

Filter a dictionary based on a constraint on the keys in a Pythonic way


Given a dictionary, I would like to get a new dictionary that is a subset of the original dictionary by checking which keys satisfy a specific constraint. For example, for a dictionary with string keys, filter to keys that start with a certain substring.

» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby': 2, 'Baboon': 3}

This is fairly simple to do with a function:

def slice(sourcedict, string):
    newdict = {}
    for key in sourcedict.keys():
        if key.startswith(string):
            newdict[key] = sourcedict[key]
    return newdict

But surely there is a nicer, cleverer, or more "readable" solution? Could a generator help here? (I never have enough opportunities to use those).


Solution

  • How about this:

    In Python 3.x :

    def slicedict(d, s):
        return {k:v for k,v in d.items() if k.startswith(s)}
    

    in Python 2.x :

    def slicedict(d, s):
        return {k:v for k,v in d.iteritems() if k.startswith(s)}