Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a sub-set of a Python dictionary

I have a dictionary:

{'key1':1, 'key2':2, 'key3':3} 

I need to pass a sub-set of that dictionary to third-party code. It only wants a dictionary containing keys ['key1', 'key2', 'key99'] and if it gets another key (eg 'key3'), it explodes in a nasty mess. The code in question is out of my control so I'm left in a position where I have to clean my dictionary.

What's the best, way to limit a dictionary to a set of keys?

Given the example dictionary and allowed keys above, I want:

{'key1':1, 'key2':2} 
like image 483
Oli Avatar asked Oct 17 '10 13:10

Oli


People also ask

How do you create a sub dictionary in Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

How do you know if a dictionary is subset of another?

Both sets have one element: One has the key value tuple "name":"Girls" and the other has the single element composed of a key value tuple "show": {"name": "Girls"} and when two sets both have one element, those elements must be equal for the sets to be considered subsets of eachother.

How do you slice a nested dictionary in Python?

Key Points to Remember:Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value. Dictionary are accessed using key.


1 Answers

In [38]: adict={'key1':1, 'key2':2, 'key3':3} In [41]: dict((k,adict[k]) for k in ('key1','key2','key99') if k in adict) Out[41]: {'key1': 1, 'key2': 2} 

In Python3 (or Python2.7 or later) you can do it with a dict-comprehension too:

>>> {k:adict[k] for k in ('key1','key2','key99') if k in adict} {'key2': 2, 'key1': 1} 
like image 189
unutbu Avatar answered Sep 18 '22 15:09

unutbu