Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract subset of key-value pairs from dictionary?

I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to achieve that?

The best I know is:

bigdict = {'a':1,'b':2,....,'z':26}  subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']} 

I am sure there is a more elegant way than this.

like image 947
Jayesh Avatar asked Mar 18 '11 13:03

Jayesh


People also ask

Can you slice a dict?

To slice a dictionary, you can use dictionary comprehension. In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements.

How do you get all the keys values from a dict?

In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values. In the above code first, we will initialize a dictionary and assign key-value pair elements.


1 Answers

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'}} 
like image 123
Mark Longair Avatar answered Sep 23 '22 20:09

Mark Longair