Extract subset of key-value pairs from dictionary?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:37 Accepted answer (Score 568)
01:39 Answer 2 (Score 145)
01:53 Answer 3 (Score 33)
02:36 Answer 4 (Score 29)
02:48 Thank you
--
Full question
https://stackoverflow.com/questions/5352...
Accepted answer links:
[Fábio Diniz]: https://stackoverflow.com/users/541842/f...
[Håvard S]: https://stackoverflow.com/users/94237/ha...
[his answer]: https://stackoverflow.com/questions/5352...
[timbo]: https://stackoverflow.com/users/127660/t...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #associativearray
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:37 Accepted answer (Score 568)
01:39 Answer 2 (Score 145)
01:53 Answer 3 (Score 33)
02:36 Answer 4 (Score 29)
02:48 Thank you
--
Full question
https://stackoverflow.com/questions/5352...
Accepted answer links:
[Fábio Diniz]: https://stackoverflow.com/users/541842/f...
[Håvard S]: https://stackoverflow.com/users/94237/ha...
[his answer]: https://stackoverflow.com/questions/5352...
[timbo]: https://stackoverflow.com/users/127660/t...
--
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')}