views:

55

answers:

2

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}
+9  A: 
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 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}
unutbu
+1  A: 
dict(filter(lambda i:i[0] in validkeys, d.iteritems()))
Space_C0wb0y