Omnipresent Omnipresent - 4 months ago 10
Python Question

Way to get specific keys from dictionary

I am looking for a way to get specific keys from a dictionary.

In the example below, I am trying to

get all keys except 'inside'

>>> d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
>>> d_keys = list(set(d.keys()) - set(["inside"]) )
>>> d_keys
['shape', 'fill', 'angle', 'size']
>>> for key in d_keys:
... print "key: %s, value: %s" % (key, d[key])
key: shape, value: unchanged
key: fill, value: unchanged
key: angle, value: unchanged
key: size, value: unchanged

Is there a better way to do this than above?


In python 3.X most of dictionary attributes like keys, return a view object which is a set-like object, so you don't need to convert it to set again:

>>> d_keys = d.keys() - {"inside",}
>>> d_keys
{'fill', 'size', 'angle', 'shape'}

Or if you are in python2.x you can use dict.viewkeys():

d_keys = d.viewkeys() - {"inside",}

But if you want to only remove one item you can use pop() attribute in order to remove the corresponding item from dictionary and then calling the keys().

>>> d.pop('inside')
>>> d.keys()
dict_keys(['fill', 'size', 'angle', 'shape'])

In python 2 since keys() returns a list object you can use remove() attribute for removing an item directly from the keys.