Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 626
Omnipresent Avatar asked Dec 02 '25 17:12

Omnipresent


2 Answers

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')
'a->e'
>>> 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.

like image 111
Mazdak Avatar answered Dec 04 '25 07:12

Mazdak


You can use remove() built-in.

d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}

d_keys = list(d.keys())
d_keys.remove('inside')

for i in d_keys:
    print("Key: {}, Value: {}".format(d_keys, d[d_keys]))
like image 20
Janarthanan .S Avatar answered Dec 04 '25 06:12

Janarthanan .S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!