Omnipresent
Omnipresent

Reputation: 30374

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?

Upvotes: 3

Views: 489

Answers (8)

Craig Burgler
Craig Burgler

Reputation: 1779

a cross-version approach:

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

d_keys = [k for k in d.keys() if k  != 'inside']

print(d_keys)

Output:

['fill', 'shape', 'angle', 'size']


expanding it a bit:

def get_pruned_dict(d, excluded_keys):
    return {k:v for k,v in d.items() if k not in excluded_keys}

exclude = ('shape', 'inside')
pruned_d = get_pruned_dict(d, exclude)

print(pruned_d)

Output

{'fill': 'unchanged', 'size': 'unchanged', 'angle': 'unchanged'}

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

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.

Upvotes: 4

Janarthanan .S
Janarthanan .S

Reputation: 11

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]))

Upvotes: 1

BPL
BPL

Reputation: 9863

Here's a little benchmark comparing a couple of good posted solutions:

import timeit

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


def f1(d):
    return d.viewkeys() - {"inside", }


def f2(d):
    return filter(lambda x: x not in ['inside'], d.viewkeys())

N = 10000000
print timeit.timeit('f1(d)', setup='from __main__ import f1, d', number=N)
print timeit.timeit('f2(d)', setup='from __main__ import f2, d', number=N)

# 5.25808963984
# 8.54371443087
# [Finished in 13.9s]

Conclusion: f1 not only is better in terms of readability but also in terms of performance. In python 3.x you'd use keys() instead.

So I'd say @Kasramvd answer is the right one for this post

Upvotes: 0

Morgan Thrapp
Morgan Thrapp

Reputation: 9986

There's not really a good way to do this if you need to keep the original dictionary the same.

If you don't, you could pop the key you don't want before getting the keys.

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

This will mutate d, so again, don't use this if you need all of d somewhere else. You could make a copy of d, but at that point you're better off just iterating over a filtered copy of d.keys(). For example:

d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
ignored_keys = ['inside']
for key in filter(lambda x: x not in ignored_keys, d.keys()):
     print "key: %s, value: %s" % (key, d[key])

Upvotes: 0

Mike Tung
Mike Tung

Reputation: 4821

you can do it with a dict comprehension for example to only get evens.

d = {1:'a', 2:'b', 3:'c', 4:'d'}
new_d = {k : v for k,v in d.items() if k % 2 == 0}

for your case because of complaints.

d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged',         'inside': 'a->e'}
new_d = {k:v for k,v in d.items() if k != 'fill'}
#you can replace the k != with whatever key or keys you want

Upvotes: -1

Himanshu dua
Himanshu dua

Reputation: 2523

for key in d_keys:
    if key not in ['inside']:
        print "key: %s, value: %s" % (key, d[key])

Upvotes: 0

Daniel Lee
Daniel Lee

Reputation: 8011

Not sure what you need with inside but this will give your result.

for key in d.keys:
    if key != 'inside':
         print "key: %s, value: %s" % (key, d[key])

Upvotes: 0

Related Questions