Extract subset of key-value pairs from dictionary? Extract subset of key-value pairs from dictionary? python python

Extract subset of key-value pairs from dictionary?


You could try:

dict((k, bigdict[k]) for k in ('l', 'm', 'n'))

... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too):

{k: bigdict[k] for k in ('l', 'm', 'n')}

Update: As Håvard S points out, I'm assuming that you know the keys are going to be in the dictionary - see his answer if you aren't able to make that assumption. Alternatively, as timbo points out in the comments, if you want a key that's missing in bigdict to map to None, you can do:

{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}

If you're using Python 3, and you only want keys in the new dict that actually exist in the original one, you can use the fact to view objects implement some set operations:

{k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}}


A bit shorter, at least:

wanted_keys = ['l', 'm', 'n'] # The keys you wantdict((k, bigdict[k]) for k in wanted_keys if k in bigdict)


interesting_keys = ('l', 'm', 'n')subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}


matomo