The Python Oracle

Extract subset of key-value pairs from dictionary?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Extract Subset Of Key-Value Pairs From Dictionary?
00:26 Accepted Answer Score 616
01:09 Answer 2 Score 153
01:20 Answer 3 Score 37
01:55 Answer 4 Score 30
02:01 Answer 5 Score 18
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/5352...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary #associativearray

#avk47



ACCEPTED ANSWER

Score 618


You could try:

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

... or in Python versions 2.7 or later:

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

I'm assuming that you know the keys are going to be in the dictionary. See the answer by HÃ¥vard S if you don't.

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'}}



ANSWER 2

Score 153


A bit shorter, at least:

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



ANSWER 3

Score 30


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



ANSWER 4

Score 18


This answer uses a dictionary comprehension similar to the selected answer, but will not except on a missing item.

python 2 version:

{k:v for k, v in bigDict.iteritems() if k in ('l', 'm', 'n')}

python 3 version:

{k:v for k, v in bigDict.items() if k in ('l', 'm', 'n')}